FileInputStream的read()方法,内存和硬盘交互太频繁,效率较低,不建议使用

1.字节流FileInputStream  read()方法一次读取一个字节  *返回值为int,返回读取的内容,为空返回-1

  一次只读一个字节,加循环进行全部读取:

  while(fileInputStream.read() != -1){
     System.out.println(fileInputStream.read());
  }
  *第一次写时把代码写成了这样,发现少了一次输出,在进行判断时已经读取了一个字节while(fileInputStream.read() != -1)
  int a = fileInputStream.read();
  while (a != -1){
  System.out.println(a);
  a = fileInputStream.read();
  }
  *写了两个重复的语句a = fileInputStream.read(),需要简化代码:
  int readDate = 0;
  while ((readDate = fileInputStream.read()) != -1){
  System.out.println(readDate);
  }
  *正确写法

2.创建流之后一定要关闭,代码写在finally语句块中

finally {
if (fileInputStream != null) {
try {
fileInputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
*第一次写时没有加判断语句if (fileInputStream != null),当没有创建流时不用关闭。避免空指针异常

补充:因为.close()要写到finally中,所以流对象的创建不能写在try语句块中
   正确写法:
      FileInputStream fileInputStream = null;
      try{
        fileInuputStream = new FileInputStream("path");
      }

posted @ 2020-08-09 09:53  javase-->  阅读(1145)  评论(0)    收藏  举报