IO流中的字节输入与字节输出流

字节输入流 

FileInputStream常用方法

read()返回值是int类型:读取一个字节的内容(读完了,返回-1)

int b = 0;
while((b = fis.read()) != -1){
    System.out.println((char) b);
}

read(byte[] buffer)读取一个字节组数,返回的不是读取的内容,而是读取了多少字节到字节数组中,返回int表示读取完了。

close()关流/释放资源(开启流之后,一定要关流)

FileInputStream fis = null;
try {
    // 指定数据源
    fis = new FileInputStream("d:/a.txt");

    // 读取数据
    byte[] buffer = new byte[6];
    fis.read(buffer);
    for (byte b : buffer) {
        
        System.out.print((char) b);
    }
} finally {
    // 关流
    if (fis != null) {
        fis.close();
    }
}

字节输出流

FileOutputStream常用方法:

  • write(int b) : void 写入一个字节数据

  • write(byte[] b) : void 写入一个字节数组的数据

  • write(byte[] b, int off, int len) : void 写入一个字节数组指定范围的数据

  • close() : void 关流

文件的复制

需求:将 d 盘的 a.txt 复制到 e 盘。

// 指定数据源和输出目的地(创建输入流和输出流)
try (FileInputStream fis = new FileInputStream("d:/a.txt");
     FileOutputStream fos = new FileOutputStream("e:/a.txt")) {​
    // 边读边写
    // 读取d盘a.txt内容
    byte[] buffer = new byte[1024];
    int len = 0;
    while ((len = fis.read(buffer)) != -1) {
        // 将读取到的内容写入e盘a.txt
        fos.write(buffer, 0, len);
    }​    System.out.println("复制成功!");
} catch (Exception e) {
    e.printStackTrace();
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值