Java InputStreamReader 和 OutputStreamWriter__java

來源:互聯網
上載者:User
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();        }     }}

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.