JAVA學習—IO—轉換流

JAVA學習—IO—轉換流


    轉換流是指將字節流與字符流之間的轉換,包含兩個類:InputStreamReader和OutputStreamWriter。

    轉換流的出現方便了對文件的讀寫,她在字符流與字節流之間架起了一座橋樑,使原本毫無關聯的兩種流操作能夠進行轉化,提高了程序的靈活性。

    InputStreamReader的構造操作:

InputStreamReader(InputStream in)
          創建一個使用默認字符集的 InputStreamReader。

InputStreamReader(InputStream in,Charset cs)
          創建使用給定字符集的 InputStreamReader。

InputStreamReader(InputStream in,CharsetDecoder dec)
          創建使用給定字符集解碼器的 InputStreamReader。

InputStreamReader(InputStream in,String charsetName)
          創建使用指定字符集的 InputStreamReader。

 

    InputStreamReader的相關操作:

 void

close()
          關閉該流並釋放與之關聯的所有資源。

 String

getEncoding()
          返回此流使用的字符編碼的名稱。

 int

read()
          讀取單個字符。

 int

read(char[] cbuf, int offset, int length)
          將字符讀入數組中的某一部分。

 boolean

ready()
          判斷此流是否已經準備好用於讀取。

    OutputStreamWriter的構造

OutputStreamWriter(OutputStream out)
          創建使用默認字符編碼的 OutputStreamWriter。

OutputStreamWriter(OutputStream out,Charset cs)
          創建使用給定字符集的 OutputStreamWriter。

OutputStreamWriter(OutputStream out,CharsetEncoder enc)
          創建使用給定字符集編碼器的 OutputStreamWriter。

OutputStreamWriter(OutputStream out,String charsetName)
          創建使用指定字符集的 OutputStreamWriter。

 

方法摘要

 void

close()
          關閉此流,但要先刷新它。

 void

flush()
          刷新該流的緩衝。

 String

getEncoding()
          返回此流使用的字符編碼的名稱。

 void

write(char[] cbuf, int off, int len)
          寫入字符數組的某一部分。

 void

write(int c)
          寫入單個字符。

 void

write(String str, int off, int len)
          寫入字符串的某一部分。

    示例如下:

package com.abin;

import java.io.BufferedReader;

import java.io.IOException;

import java.io.InputStream;

import java.io.InputStreamReader;

public class InputStreamReaderDemo {

    public static void main(String[] args) throws IOException {

        //獲取標準輸入流

        InputStreamin = System.in;

        //將字節流轉換爲字符流

        InputStreamReaderisr = new InputStreamReader(in);

        //將字符流裝飾

        BufferedReaderbr = new BufferedReader(isr);

        Stringstring =null;

        while ((string=br.readLine())!=null) {

            if ("over".equals(string)) {

                break;

            }

            System.out.println(string.toUpperCase());

        }

    }

}

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章