通过之前一次读取一个字节数据的示例中,发现当读取到流的末尾是会返回-1,读取字节数组时同样也是返回-1时作为终止循环的条件
public class FileInputDemo01 { public static void main(String[] args) throws IOException { //创建字节输入流对象 FileInputStream fis = new FileInputStream("myFile\\fos.txt"); //调用字节输入流对象的读数据方法 //int read(byte[] b):从该输入流读取最多 b.length个字节的数据为字节数组。 //首先要有一个字节数组作为存储数据的容器 byte[] bys = new byte[1024]; int len; //len代表读取到的数据的长度 /* len变量的含义:假如字节数组中有5个字节数据时,该值等于5,有100个字节数据时,该值就等于100 */ while ((len = fis.read(bys)) != -1) { //String(byte[] bytes, int offset, int length) System.out.println(new String(bys,0,len)); } //释放资源 fis.close(); } }
fos.txt中内容为:
运行结果:
修改fos.txt内容:
运行结果: