Java InputStreamReader 和 OutputStreamWriter
InputStreamReader
InputStreamReader 是位元組流通向字元流的橋樑:它使用指定的 charset 讀取位元組並將其解碼為字元。它使用的字元集可以由名稱指定或顯式給定,或者可以接受平台預設的字元集。
構造方法
| 構造方法 |
說明 |
| InputStreamReader(InputStream in) |
建立一個使用預設字元集的 InputStreamReader |
| InputStreamReader(InputStream in, String charsetName) |
建立使用指定字元集的 InputStreamReader |
方法
| 方法 |
說明 |
| getEncoding() |
返回此流使用的字元編碼的名稱 |
| read() |
讀取單個字元 |
| read(char[] cbuf, int offset, int length) |
將字元讀入數組中的某一部分 |
| close() |
關閉該流並釋放與之關聯的所有資源 |
OutputStreamWriter
OutputStreamWriter 是字元流通向位元組流的橋樑:可使用指定的 charset 將要寫入流中的字元編碼成位元組。它使用的字元集可以由名稱指定或顯式給定,否則將接受平台預設的字元集。
構造方法
| 構造方法 |
說明 |
| OutputStreamWriter(OutputStream out) |
建立使用預設字元編碼的 OutputStreamWriter |
| OutputStreamWriter(OutputStream out, String charsetName) |
建立使用指定字元集的 OutputStreamWriter |
方法
| 方法 |
說明 |
| getEncoding() |
返回此流使用的字元編碼的名稱 |
| write(int c) |
寫入單個字元 |
| write(char[] cbuf, int off, int len) |
寫入字元數組的某一部分 |
| write(String str, int off, int len) |
寫入字串的某一部分 |
| close() |
關閉此流,但要先重新整理它 |
拷貝檔案樣本
InputStreamReader input = null;OutputStreamWriter output = null;try { // 建立輸入輸出資料流,並制定字元編碼集 input = new InputStreamReader(new FileInputStream("E:/readme.txt"), "utf-8"); output = new OutputStreamWriter(new FileOutputStream("D:/temp.txt"), "utf-8"); char[] buffer = new char[1024 * 8]; int len; // 讀寫資料 while((len = input.read(buffer)) > 0) { output.write(buffer, 0, len); } // 一定要重新整理,確保緩衝區內資料全部寫入檔案 output.flush(); System.out.println("Done.");} catch (IOException e) { try { // 關閉輸入資料流 if(input != null) { input.close(); } } catch (IOException e2) { e.printStackTrace(); } finally { try { // 關閉輸出資料流 if(output != null) { output.close(); } } catch (IOException e3) { e.printStackTrace(); } }}