Day16_94_IO_循环读取文件字节流read()方法(二)
循环读取文件字节流read()方法
-
通过read()循环读取数据,但是read()每次都只能读取一个字节,频繁读取磁盘对磁盘有伤害,且效率低。
import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.IOException; public class IOTest02 { public static void main(String[] args) { //创建文件路径对象 String filename="D:\\TestFile\\JavaTestFile\\IoTest.txt"; //创建文件字节输入流 FileInputStream fis=null; try { fis= new FileInputStream(filename); //开始读取文件字节流 /*方式一 while(true){ int temp=fis.read(); if(temp==-1){ break; } System.out.println(temp); }*/ //方式二 int temp=0; while ((temp=fis.read())!=-1){ System.out.println(temp); } } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } finally { if(fis!=null){ try { fis.close(); } catch (IOException e) { e.printStackTrace(); } } } } }