標籤:有一個 otf 實現 功能 void 一個 print rac trace
1. 位元組流和字元流的區別:
位元組流操作的資料單元是8位的位元組,而字元流操作的資料單元是16位的字元。
2. 節點流和處理流的區別:
可以從/向一個特定的IO裝置(如磁碟、網路)讀、寫資料的流,稱為節點流,也被稱為低級流。
處理流則用於對一個已經存在的流進行串連或封裝,通過封裝後的流實現資料讀寫功能。
3. InputStream 和 Reader
InputStream 和 Reader 是所有輸入資料流的抽象基類,本身不能建立執行個體或執行輸入,但成為所有輸入資料流的模板,它們的方法是所有輸入資料流都可使用的方法。
InputStream包含如下方法:
//從輸入資料流種讀取單個位元組,返回所讀取的位元組資料int read(); //從輸入資料流種最多讀取b.length個位元組的資料,並儲存在位元組數組b種,返回實際讀取的位元組數int read(byte b[]);//從輸入資料流中最多讀取len個字元的資料,並將其儲存在字元數組buff中,並不是從數組起點開始,而是從off位置開始int read(byte b[], int off, int len)
Reader包含如下方法:
//從輸入資料流中讀取單個字元,返回所讀取的字元資料int read();//從輸入資料流中最多讀取cbuf.length個字元資料,並儲存在cbuf中,返回實際讀取的字元數int read(char cbuf[]);//從輸入資料流中最多讀取cbuf.length個字元資料,並儲存在cbuf中,從off開始儲存,返回實際讀取的字元數int read(char cbuf[], int off, int len);
InputStream和Reader是抽象基類,本身不能建立執行個體,但它們分別有一個用於讀取檔案的輸入資料流: FileInputStream, FileReader
public class FileInputStreamTest { public static void main(String[] args) { InputStream fis = null; try { fis = new FileInputStream("D:/rding/testfile2/file.txt"); byte[] bbuf = new byte[1024]; int hasRead = 0; while ((hasRead = fis.read(bbuf)) > 0) { System.out.println(new String(bbuf, 0, hasRead)); } } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } finally { try { if (fis != null) { fis.close(); } } catch (IOException e) { e.printStackTrace(); } } }}
public class FileReaderTest { public static void main(String[] args) { Reader fr = null; try { fr = new FileReader("D:/rding/testfile2/file.txt"); char[] cbuf = new char[32]; int hasRead = 0; while ((hasRead = fr.read(cbuf)) > 0) { System.out.print(new String(cbuf, 0, hasRead)); } } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } finally { if (fr != null) { try { fr.close(); } catch (IOException e) { e.printStackTrace(); } } } }}
Java InputStream和Reader