java io学习(二十) InputStreamReader和OutputStreamWriter2014-08-12InputStreamReader和OutputStreamWriter 是字节流通向字符流的桥梁:它使用指定的 charset 读写字节并将其解码为字符。InputStreamReader 的作用是将“字节输入流”转换成“字符输入流”。它继承于Reader。OutputStreamWriter 的作用是将“字节输出流”转换成“字符输出流”。它继承于Writer。InputStreamReader和OutputStreamWriter源码分析1. InputStreamReader 源码(基于jdk1.7.40)
package java.io; import java.nio.charset.Charset;import java.nio.charset.CharsetDecoder;import sun.nio.cs.StreamDecoder;// 将“字节输入流”转换成“字符输入流”public class InputStreamReader extends Reader { private final StreamDecoder sd; // 根据in创建InputStreamReader,使用默认的编码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 availablethrow new Error(e);}} // 根据in创建InputStreamReader,使用编码charsetName(编码名)public InputStreamReader(InputStream in, String charsetName)throws UnsupportedEncodingException{super(in);if (charsetName == null)throw new NullPointerException("charsetName");sd = StreamDecoder.forInputStreamReader(in, this, charsetName);} // 根据in创建InputStreamReader,使用编码cspublic InputStreamReader(InputStream in, Charset cs) {super(in);if (cs == null)throw new NullPointerException("charset");sd = StreamDecoder.forInputStreamReader(in, this, cs);} // 根据in创建InputStreamReader,使用解码器decpublic 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();} // 将InputStreamReader中的数据写入cbuf中,从cbuf的offset位置开始写入,写入长度是lengthpublic int read(char cbuf[], int offset, int length) throws IOException {return sd.read(cbuf, offset, length);} // 能否从InputStreamReader中读取数据public boolean ready() throws IOException {return sd.ready();} // 关闭InputStreamReaderpublic void close() throws IOException {sd.close();}}