Java-IO之InputStreamReader和OutputStreamWriter

时间:2021-08-08 22:42:54
InputStreamReader和OutputStreamWriter是字节流通向字符流的桥梁。它使用指定的差染色体读写字节并将其解码为字符。InputStreamReader的作用是将字节输入流转换成字符输入流,继承于Reader。OutputStreamWriter是作用是字节输出流转换成字符输出流,继承于Writer。

InputStreamReader和OutputStreamWriter的示例代码

public class StreamConverter {

    private static final String FileName = "file.txt";
    private static final String CharsetName = "utf-8";
    //private static final String CharsetName = "gb2312";

    public static void main(String[] args) {
        testWrite();
        testRead();
    }

    /**
     * OutputStreamWriter 演示函数
     *
     */
    private static void testWrite() {
        try {
            // 创建文件“file.txt”对应File对象
            File file = new File(FileName);
            // 创建FileOutputStream对应OutputStreamWriter:将字节流转换为字符流,即写入out1的数据会自动由字节转换为字符。
            OutputStreamWriter out1 = new OutputStreamWriter(new FileOutputStream(file), CharsetName);
            // 写入10个汉字
            out1.write("字节流转为字符流示例");
            // 向“文件中”写入"0123456789"+换行符
            out1.write("0123456789\n");
            out1.close();

        } catch(IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * InputStreamReader 演示程序
    */
    private static void testRead() {
        try {
            // 方法1:新建FileInputStream对象
            // 新建文件“file.txt”对应File对象
            File file = new File(FileName);
            InputStreamReader in1 = new InputStreamReader(new FileInputStream(file), CharsetName);

            // 测试read(),从中读取一个字符
            char c1 = (char)in1.read();
            System.out.println("c1="+c1);

            // 测试skip(long byteCount),跳过4个字符
            in1.skip(6);

            // 测试read(char[] cbuf, int off, int len)
            char[] buf = new char[10];
            in1.read(buf, 0, buf.length);
            System.out.println("buf="+(new String(buf)));

            in1.close();
        } catch(IOException e) {
            e.printStackTrace();
        }
    }
}

运行结果:
c1=字
buf=流示例0123456

基于JDK8的InputStreamReader的源码:

public class InputStreamReader extends Reader {

    private final StreamDecoder sd;

    //构造函数,使用平台默认的字符类型
    public InputStreamReader(InputStream in) {
        super(in);
        try {
            sd = StreamDecoder.forInputStreamReader(in, this, (String)null); // ## check lock object
        } catch (UnsupportedEncodingException e) {
            // The default encoding should always be available
            throw new Error(e);
        }
    }

    /**
     * Creates an InputStreamReader that uses the named charset.
     *
     * @param  in
     *         An InputStream
     *
     * @param  charsetName
     *         The name of a supported
     *         {@link java.nio.charset.Charset charset}
     *
     * @exception  UnsupportedEncodingException
     *             If the named charset is not supported
     */
    //构造函数,使用提供的字符类型
    public InputStreamReader(InputStream in, String charsetName)throws UnsupportedEncodingException
    {
        super(in);
        if (charsetName == null)
            throw new NullPointerException("charsetName");
        sd = StreamDecoder.forInputStreamReader(in, this, charsetName);
    }

    //构造函数,使用提供的字符类型
    public InputStreamReader(InputStream in, Charset cs) {
        super(in);
        if (cs == null)
            throw new NullPointerException("charset");
        sd = StreamDecoder.forInputStreamReader(in, this, cs);
    }
    //使用提供的字符译码器
    public InputStreamReader(InputStream in, CharsetDecoder dec) {
        super(in);
        if (dec == null)
            throw new NullPointerException("charset decoder");
        sd = StreamDecoder.forInputStreamReader(in, this, dec);
    }

    //返回字符编码
    public String getEncoding() {
        return sd.getEncoding();
    }

    //读单个字符
    public int read() throws IOException {
        return sd.read();
    }
    //读字符到cbuf中
    public int read(char cbuf[], int offset, int length) throws IOException {
        return sd.read(cbuf, offset, length);
    }
    //是否准备好读
    public boolean ready() throws IOException {
        return sd.ready();
    }
    //关闭资源
    public void close() throws IOException {
        sd.close();
    }
}

基于JDK8的OutputStreamWriter的源码:

public class OutputStreamWriter extends Writer {

    private final StreamEncoder se;
    //构造函数,使用被命名的字符集
    public OutputStreamWriter(OutputStream out, String charsetName)throws UnsupportedEncodingException
    {
        super(out);
        if (charsetName == null)
            throw new NullPointerException("charsetName");
        se = StreamEncoder.forOutputStreamWriter(out, this, charsetName);
    }
    //构造函数,使用系统默认的字符集
    public OutputStreamWriter(OutputStream out) {
        super(out);
        try {
            se = StreamEncoder.forOutputStreamWriter(out, this, (String)null);
        } catch (UnsupportedEncodingException e) {
            throw new Error(e);
        }
    }
    //构造函数,使用给定的字符集
    public OutputStreamWriter(OutputStream out, Charset cs) {
        super(out);
        if (cs == null)
            throw new NullPointerException("charset");
        se = StreamEncoder.forOutputStreamWriter(out, this, cs);
    }
    //构造函数,使用给定的字符编码器
    public OutputStreamWriter(OutputStream out, CharsetEncoder enc) {
        super(out);
        if (enc == null)
            throw new NullPointerException("charset encoder");
        se = StreamEncoder.forOutputStreamWriter(out, this, enc);
    }
    //获得编码器
    public String getEncoding() {
        return se.getEncoding();
    }
    //刷新缓冲区,
    void flushBuffer() throws IOException {
        se.flushBuffer();
    }
    //写单个字符
    public void write(int c) throws IOException {
        se.write(c);
    }
    //写字符数组的一部分
    public void write(char cbuf[], int off, int len) throws IOException {
        se.write(cbuf, off, len);
    }
    //写字符串的一部分
    public void write(String str, int off, int len) throws IOException {
        se.write(str, off, len);
    }
    //刷新流
    public void flush() throws IOException {
        se.flush();
    }
    //关闭资源
    public void close() throws IOException {
        se.close();
    }
}