IO流学习之字节流读取

      • 输入流
        • 字符流(记事本能打开的文本文件)
        • 字节流(万能流)
          • InputStream
            • 构造方法
              • FileInputStream(file) 与FileOutputStream的构造方法基本一致
              • 同样在调用这个时需要注意close方法释放资源和异常处理。
            • read()方法读取数据,这里用到String(byte[] bytes, int offset, int length)
        •     
      •  
package zxj.day16.IODemo;

import java.io.FileInputStream;
import java.io.IOException;

public class InputStreamDemo01 {
public static void main(String[] args) {
FileInputStream fis = null;
try {

fis = new FileInputStream("C:\\Users\\Zero\\Desktop\\zxj\\zxj.txt");
byte[] bytes = new byte[1024];
int len;
/*
* 利用while循环1kb的读取数据,当数据读取完之后fis.read(bytes)结果会等于-1
* 进而将整个文件所有内容读取完毕
* */
while ((len = fis.read(bytes)) != -1) {

/*这里用到了String的构造方法
String(byte[] bytes, int offset, int length)
通过使用平台的默认字符集解码指定的字节子阵列来构造新的 String 。
返回一个字符串*/

System.out.println(new String(bytes,0,len));
}
} catch (IOException ioe) {
ioe.printStackTrace();
}finally {
//前面的try结构当中如果出现异常,fis则为null,而调用close方法会导致空指针异常
if (fis != null) {
try {
fis.close();
} catch (IOException ioe) {
ioe.printStackTrace();
}
}
}

}
}

posted @ 2020-09-16 21:41  ZeroDuck  阅读(232)  评论(0)    收藏  举报