親愛的樂字節的小夥伴們,小樂又來分享Java技術文章了。上一篇寫到了IO流,這篇文章着重 談談輸入流,再下次再說輸出流。java
點擊回顧上一篇:樂字節Java之file、IO流基礎知識和操做步驟數組
字節流和字符流的操做方式幾乎徹底同樣,只是操做的數據單元不一樣而已 。字節流可jvm
以操做全部文件,字符流僅操做純文本。性能
InputStream和Reader是全部輸入流的基類,它們是兩個抽象類,是全部輸入流的模版,其中定義的方法在全部輸入流中均可以使用。學習
在InputStream裏包含以下三個方法:編碼
在Reader中包含以下三個方法:spa
對比InputStream和Reader 所提供的方法,能夠看出這兩個基類的功能基本類似。返回結果爲-1 時代表到了輸入流的結束點。 InputStream 和 Reade 都是抽象的,不能直接建立它們的實例,可使用它們的子類。code
FileInputStream 和 FileReader,它們都是節點流,直接和指定文件關聯。 操做方式對象
基本一致。blog
1)、單個字節讀取
以FileInputStream爲例:
public class SingleFileRead { public static void main(String[] args) { // 一、創建聯繫 File對象 File file = new File("f:/IO/test.txt"); // 二、選擇流 InputStream in = null;// 提高做用域 try { in = new FileInputStream(file); // 三、操做 單個字節讀取 long fileLength = file.length(); // 接收實際讀取的字節數 // 計數器 System.out.println(fileLength); long num = 0; // 循環讀取 while (num < fileLength) { char ch = (char) in.read(); System.out.println(ch); num++; } } catch (FileNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); System.out.println("文件不存在,不能進行下一步操做"); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); System.out.println("讀取文件失敗"); } finally { try { // 四、釋放資料 if (in != null) { in.close(); } } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); System.out.println("關閉文件輸入流失敗"); } } } } 樂字節原創
2)、批量讀取(字節|字符重點)
public class ReadFile { public static void main(String[] args) { //一、字節讀取:創建聯繫 File對象 File file=new File("f:/IO/test.txt"); //二、選擇流 InputStream in=null;//提高做用域 try { in=new FileInputStream(file); //三、操做 不斷讀取 緩衝數組 byte[]car=new byte[1024]; int len=0; //接收實際讀取的大小 //循環讀取 while(-1!=(len=in.read(car))){ //輸出,字節數組轉成字符串 String info=new String(car,0,len); System.out.println(info); } } catch (FileNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); System.out.println("文件不存在"); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); System.out.println("讀取文件失敗"); }finally{ try { //四、釋放資料 if(in!=null){ in.close(); } } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); System.out.println("關閉文件輸入流失敗"); } } } } //字符讀取一、建立源 File src=new File("f:/char.txt"); //二、選擇流 Reader reader=new FileReader(src); //三、讀取操做 char[] flush=new char[1024]; int len=0; while(-1!=(len=reader.read(flush))){ //字符數組轉換爲字符串 String str=new String(flush,0,len); System.out.