【輸入流中的字符流和字節流】
【InputStream和Reader】
InputStream和Reader是所有輸入流的抽象基類,本身不能實例化,但是他們是所有輸入流的模板。
[ InputStream包含的方法 ]
int read() 從輸入流中讀去單個字節,返回讀取的字節數。(字節類型轉換成int類型)
int read( byte[] b ) 從輸入流中最多讀取b.length個字節的數據,將數據存儲在字節數組b中,返回讀取的字節數。
int read( byte[] b, int off, int len ) 從輸入流中最多讀取len個字節的數據,並將其存儲在字節數組b中,並不是從數組起點開始,而是從off位置開始,返回讀取的字節數。
[ Reader包含的方法 ]
int read() 從輸入流中讀去單個字符,返回讀取的字符數。(字符類型轉換成int類型)
int read( char[] c ) 從輸入流中最多讀取c.length個字符的數據,將數據存儲在字符數組c中,返回讀取的字符數。
int read( char[] c, int off, int len ) 從輸入流中最多讀取len個字符的數據,並將其存儲在字符數組c中,並不是從數組起點開始,而是從off位置開始,返回讀取的字符數。
【測試1:FileInputStream讀取文件中的數據,並打印到控制台】
package com.Higgin.part3; import java.io.FileInputStream; public class FileInputStreamDemo { public static void main(String[] args) throws Exception { FileInputStream fis=new FileInputStream("c://testJavaIO/aaa.java"); //創建字節輸入流 byte[] bbuf=new byte[1024]; //創建一個字節長度為1024的緩存,即"竹筒" int hasRead=0; //用於保存每次實際讀取的字節數 int i=0; while((hasRead=fis.read(bbuf))>0){ //如果取得數據為-1或0,說明上一次已經取完所有數據 System.out.println(new String(bbuf,0,hasRead)); System.out.println("i------"+i); i++; } fis.close();//關閉文件輸入流 } }
【想要提取的文件中的內容】
【運行結果】
【將上面代碼中的緩存數組的長度修改為80,即改為" byte[] bbuf=new byte[80]; "后的運行結果】
【測試2:FileReader讀取文件中的數據,並打印到控制台】
package com.Higgin.part3; import java.io.FileReader; import java.io.IOException; public class FileReadDemo { public static void main(String[] args) throws IOException { FileReader fr=new FileReader("c://testJavaIO/aaa.java"); char[] cbuf=new char[1024]; //創建一個字符長度為32的緩存,即"竹筒" int hasRead=0; //用於保存實際讀取的字符數 int i=0; while((hasRead=fr.read(cbuf))>0){ System.out.println(new String(cbuf,0,hasRead)); //每次取得緩存中的字符數組cbuf,將字符數組轉化成字符串輸出 System.out.println("i------"+i); i++; } fr.close(); } }
【運行結果】