FileInputStream的read方法
解释一下:
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));
输出