1. 字元流
在程式中一個字元等於兩個位元組,Java為我們提供了Reader和Writer兩個專門操作字元流的類
1) 字元輸出資料流:Writer
Writer是一個字元流,它是一個抽象類別,所以要使用它,也必須通過其子類來執行個體化它後才能使用它。
Writer類的常用方法
方法名稱 |
描述 |
public abstract void close() throws IOException |
關閉輸出資料流 |
public void write(String str) throws IOException |
將字串輸出 |
public void write(char cbuf) throws IOException |
將字元數組輸出 |
public abstract void flush() throws IOException |
強制性清空緩衝 |
樣本1:HelloWorld
向一個文字檔中通過字元輸出資料流寫入資料
public static void main(String[] args) throws Exception { // 聲明一個File對象 File file = new File("hellowolrd.txt"); // 聲明一個Write對象 Writer writer = null; // 通過FileWriter類來執行個體化Writer類的對象並以追加的形式寫入 writer = new FileWriter(file, true); // 聲明一個要寫入的字串 String str = "字串形式寫入Helloworld"; // 寫入文字檔中 writer.write(str); // 重新整理 writer.flush(); // 關閉字元輸出資料流 writer.close(); }
2) 字元輸入資料流:Reader
Reader本身也是一個抽象類別,同樣,如果使用它,我們需要通過其子類來執行個體化它才可以使用它。
Reader類的常用方法
方法名稱 |
描述 |
public abstract void close() throws IOException |
|
public int read() throws IOException |
|
public int read(char cbuf) throws IOException |
|
通過方法我們看到Reader類只提供了一個讀入字元的方法
樣本2:還是Helloworld
在上面的基礎上把文本中的內容讀出來,並且顯示在控制台上
public static void main(String[] args) throws Exception { // 聲明一個File對象 File file = new File("hellowolrd.txt"); // 聲明一個Reader類的對象 Reader reader = null; // 通過FileReader子類來執行個體化Reader對象 reader = new FileReader(file); // 聲明一個字元數組 char[] c = new char[1024];// // 將內容輸出// int len = reader.read(c); //迴圈方式一個一個讀 int len=0; int temp=0; while((temp=reader.read())!=-1){ c[len]=(char)temp; len++; } // 關閉輸入資料流 reader.close(); // 把char數群組轉換成字串輸出 System.out.println(new String(c, 0, len)); }
2. 字元流與位元組流的區別
操作位元組流操作時本身不會用到緩衝區,是檔案本身直接操作,而位元組流在操作時就使用到了緩衝區。
如果我們在操作字元流的時候,不關閉流,我們寫入的資料是無法儲存的。所以在操作字元流的時候一定要記得關閉流