IO--ReaderAndWriter

Reader and Writer:

Reader按照自定義的編碼從輸入流中進行讀取

Writer按照自定義的編碼寫入輸出流

InputStreamReader:

在初始化的時候傳入自定義的編碼以及輸入流,並生成解碼器進行讀操作。

public InputStreamReader(InputStream in, String charsetName)
        throws UnsupportedEncodingException
    {
        super(in);
        if (charsetName == null)
            throw new NullPointerException("charsetName");
        sd = StreamDecoder.forInputStreamReader(in, this, charsetName);
    }

在read的時候調用解碼器的read方法

public int read() throws IOException {
        return sd.read();
    }
觀察一下可以發現InputStreamReader使用了適配器的設計模式,在InputStream的read方法外加了一層Reader的read方法的殼,同時增加了按照固定編碼進行解碼的功能。

OutputStreamWriter:

在初始化的時候傳入自定義的編碼以及輸出流,並生成編碼器進行寫操作。

public OutputStreamWriter(OutputStream out, String charsetName)
        throws UnsupportedEncodingException
    {
        super(out);
        if (charsetName == null)
            throw new NullPointerException("charsetName");
        se = StreamEncoder.forOutputStreamWriter(out, this, charsetName);
    }

在write的時候調用編碼器的write方法

public void write(int c) throws IOException {
        se.write(c);
    }

Reader和Writer的不同:

Reader的read方法直接返回讀取的值

public int read(char cbuf[]) throws IOException {
        return read(cbuf, 0, cbuf.length);
    }
Writer的write方法將數據寫入Writer中的writerBuffer中,如果需要往輸出流裏寫的話需要調用flash或者close方法

public void write(String str, int off, int len) throws IOException {
        synchronized (lock) {
            char cbuf[];
            if (len <= WRITE_BUFFER_SIZE) {
                if (writeBuffer == null) {
                    writeBuffer = new char[WRITE_BUFFER_SIZE];
                }
                cbuf = writeBuffer;
            } else {    // Don't permanently allocate very large buffers.
                cbuf = new char[len];
            }
            str.getChars(off, (off + len), cbuf, 0);
            write(cbuf, 0, len);
        }
    }
裝飾類:

PrintWriter,BufferedWriter,BufferedReader


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