package cn.dali3.code17;
/*方法: FileInputStream类的 int read(byte [] b)
* 从输入流中读取一定数量的字节,放到缓冲区数组b中
* byte [] b的作用:缓冲作用,存储每次读到的字节
* 数组的长度一般定义为1024的整数倍
* 方法的返回值: 每次读取的有效字节个数,返回-1表示结尾
* 原理: 看方法2,首先定义的数组长度为2,索引从0-1,文本内容为ABCD四个字节
* 第一次读取 缓冲区数组 0索引为A 1索引为B 返回有效字节数为2
* 第二次读取 缓冲区数组 0索引被覆盖文C, 1索引被覆盖为D 有效字节数2
* 第三次读取 发现文本已经结束 所以0和1索引不会被覆盖 还是C和D 有效字节数为-1
*
* 复习:
* String类的两种构造方法 String(byte [] b) 数组转换为字符串
* String(byte [] b,int offset,int length)
* 字节数组 索引起始位置 索引长度*/
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
/*一次性读取多个字节*/
public class Demo02 {
public static void main(String[] args) throws IOException {
f1("C:\\Users\\Administrator\\Desktop\\新建文件夹\\a.txt");
//f2("C:\\Users\\Administrator\\Desktop\\新建文件夹\\a.txt");
}
private static void f1(String str) throws IOException {
File file = new File(str);
FileInputStream fis = new FileInputStream(file);
int len = 0;
byte[] b1 = new byte[1024];
len = fis.read(b1);
System.out.println(new String(b1, 0, len));
fis.close();
}
private static void f2(String str) throws IOException {
File file = new File(str);
FileInputStream fis = new FileInputStream(file);
int len = 0;
byte[] b2 = new byte[2];
len = fis.read(b2);
System.out.println(len);//2
System.out.println(new String(b2));//AB
len = fis.read(b2);
System.out.println(len);//2
System.out.println(new String(b2));//CD
len = fis.read(b2);
System.out.println(len);//-1
System.out.println(new String(b2));//CD
}
}
从字节输入流中读取多个字节的方法
最新推荐文章于 2022-05-19 17:35:09 发布