天天看点

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