今天学习了FileInputStream,一开始使用的第一种写法,结果发现不正确,于是寻找原因。
准备的txt文件内容
第一种代码
try {
FileInputStream fileOutputStream=new FileInputStream("ruoyi-admin/src/main/java/com/ruoyi/test/io/io.txt");
while (fileOutputStream.read()!=-1){
System.out.println(fileOutputStream.read());
}
} catch (IOException e) {
throw new RuntimeException(e);
}
结果
第二种代码
try {
FileInputStream fileOutputStream=new FileInputStream("ruoyi-admin/src/main/java/com/ruoyi/test/io/io.txt");
int read;
while ((read=fileOutputStream.read())!=-1){
System.out.println(read);
}
System.out.println(fileOutputStream.read());
} catch (IOException e) {
throw new RuntimeException(e);
}
结果
两种写法的结果不一样,但是明显的是第二种遍历的结果才是正确的,
原因是FileInputStream 中的read()方法只要调用一次指针的位置就会往后挪一位。第一种方法,遍历一次就执行了两次read()方法,进入第一次到循环体时就执行第二次read()方法,所以输出98,第二次进入循环体就执行第四次read()方法,此时txt中的内容已在第二次判断时read完毕,指针后无字节,自动返回-1。