FileInputStream的int read()、int read(byte[] b)、int read(byte[] b, int off, int len)

本文详细解析了FileInputStream的int read()、int read(byte[] b)和int read(byte[] b, int off, int len)三个方法的用法。通过实例代码展示了如何读取文件内容,包括单个字节读取、字节数组读取以及指定偏移量和长度的读取,并阐述了在文件末尾时返回-1的逻辑。
摘要由CSDN通过智能技术生成

在这里插入图片描述
解释一下:

int read() :

(1)读取一个字节数据并返回(以int型返回)
(2)再次调用读取下个未读字节
(3)文件末尾返回-1(一个真实数据也没读到)
演示文件
在这里插入图片描述
代码

FileInputStream fileInputStream = new FileInputStream(new File("E:\\aa.txt"));
        int read1 = fileInputStream.read();
        int read2 = fileInputStream.read();
        int read3 = fileInputStream.read();
        System.out.println(read1);
        System.out.println(read2);
        System.out.println(read3);

输出
在这里插入图片描述

int read(byte[] b) :

(1)读取数据存储在b数组中,一次读取b.length个字节
(2)返回读取的数据真实长度(有可能b数组长度是100,但是真实数据只有5个,则返回5)
(3)再次调用从下个未读字节开始读
(4)文件末尾返回-1(一个真实数据也没读到)
演示文件
在这里插入图片描述
代码

FileInputStream fileInputStream = new FileInputStream(new File("E:\\aa.txt"));

        byte[] bytes1=new byte[5];
        int read1 = fileInputStream.read(bytes1);
        System.out.println(read1);
        System.out.println(Arrays.toString(bytes1));

        byte[] bytes2=new byte[5];
        int read2 = fileInputStream.read(bytes2);
        System.out.println(read2);
        System.out.println(Arrays.toString(bytes2));

        byte[] bytes3=new byte[5];
        int read3 = fileInputStream.read(bytes3);
        System.out.println(read3);
        System.out.println(Arrays.toString(bytes3));

输出
在这里插入图片描述

int read(byte[] b, int off, int len) :

(1)将读到的数据存储到b中
(2)从数组下标off(包括)开始存储,读取len个字节(len<=b.length-off)
(3)返回读取的数据真实长度
(4)再次调用从下个未读字节开始读
(5)文件末尾返回-1(一个真实数据也没读到)
演示文件
在这里插入图片描述

代码

FileInputStream fileInputStream = new FileInputStream(new File("E:\\aa.txt"));
        
        byte[] bytes1=new byte[5];
        int read1 = fileInputStream.read(bytes1, 2, 3);
        System.out.println(read1);
        System.out.println(Arrays.toString(bytes1));

        byte[] bytes2=new byte[5];
        int read2 = fileInputStream.read(bytes2, 2, 3);
        System.out.println(read2);
        System.out.println(Arrays.toString(bytes2));

        byte[] bytes3=new byte[5];
        int read3 = fileInputStream.read(bytes2, 2, 3);
        System.out.println(read3);
        System.out.println(Arrays.toString(bytes3));

输出
在这里插入图片描述

  • 0
    点赞
  • 10
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

齊 天 大 聖

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

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

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

打赏作者

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

抵扣说明:

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

余额充值