Java IO(2) 字节流 FileInputStream和FileOutputStream实现文件拷贝

一、FileInputStream

FileInputStream可以按照字节的单位处理文件。

1 构造方法

在这里插入图片描述

2 方法

在这里插入图片描述

二、FileOutputStream

1 构造方法

FileOutputStream(File file)创建文件输出流以写入由指定的 File对象表示的文件。目标文件存在会覆盖原内容。
FileOutputStream(File file, boolean append)append=true表示文件目标文件存在继续追加内容。
FileOutputStream(FileDescriptor fdObj)创建文件输出流以写入指定的文件描述符,表示与文件系统中实际文件的现有连接。
FileOutputStream(String name)创建文件输出流以指定的名称写入文件。
FileOutputStream(String name, boolean append)创建文件输出流以指定的名称写入文件。 append=true表示文件目标文件存在继续追加内容。

2 方法

在这里插入图片描述

三、实现文件拷贝

1 每次读取1个字节

@Test
@DisplayName("使用字节流,每次读取1个字节")
public void testFileInputStream() throws IOException {
    String inputImgPath = "src/main/resources/static/test1.jpg";
    String outputImgPathFor = "src/main/resources/static/test2.jpg";
    File inputImgFile = new File(inputImgPath);
    File outputImgFile = new File(outputImgPathFor);
    int readData = 0;
    try (InputStream is = new FileInputStream(inputImgFile);
         OutputStream os = new FileOutputStream(outputImgFile)
    ) {
        while ((readData = is.read()) != -1) {
            os.write(readData);
        }
    } catch (IOException e) {
        e.printStackTrace();
    }
}

2 每次读取字节数组

@Test
@DisplayName("使用字节流,每次读取1024个字节")
public void testFileInputStreamWithByteArray() throws IOException {
    String inputImgPath = "src/main/resources/static/test1.jpg";
    String outputImgPathFor = "src/main/resources/static/test2.jpg";
    File inputImgFile = new File(inputImgPath);
    File outputImgFile = new File(outputImgPathFor);
    int readLength = 0;
    byte[] bytes = new byte[1024];
    try (InputStream is = new FileInputStream(inputImgFile);
         OutputStream os = new FileOutputStream(outputImgFile)
    ) {
        while ((readLength = is.read(bytes)) != -1) {
            os.write(bytes, 0, readLength);
        }
    } catch (IOException e) {
        e.printStackTrace();
    }
}
  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

为啥总是用户昵称已存在

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值