该类继承自Reader类
引入了如下包:
import java.nio.charset.Charset; import java.nio.charset.CharsetDecoder; import sun.nio.cs.StreamDecoder;
类头注释如下
/** * An InputStreamReader is a bridge from byte streams to character streams: It * reads bytes and decodes them into characters using a specified {@link * java.nio.charset.Charset charset}. The charset that it uses * may be specified by name or may be given explicitly, or the platform's * default charset may be accepted. * * <p> Each invocation of one of an InputStreamReader's read() methods may * cause one or more bytes to be read from the underlying byte-input stream. * To enable the efficient conversion of bytes to characters, more bytes may * be read ahead from the underlying stream than are necessary to satisfy the * current read operation. * * <p> For top efficiency, consider wrapping an InputStreamReader within a * BufferedReader. For example: * * <pre> * BufferedReader in * = new BufferedReader(new InputStreamReader(System.in)); * </pre> * * @see BufferedReader * @see InputStream * @see java.nio.charset.Charset * * @author Mark Reinhold * @since JDK1.1 */
大意如下:
该类是从byte流转换到字符流的桥梁
该类读取byte并编码为指定类型(Charset声明)的字符
使用字符集可由名称指定或者显式指定,或者使用平台默认字符集
每一次对该类read方法调用的时候都会从底层流读入一个或多个字节
要有效的将字节转化为字符格式,可能需要提前读入更多的字节来满足最低转化要求
为了达到最高效率,可以用BufferedReader来包装InputStreamReader
该类含有如下的成员变量:
流字节解码工具同时也是底层流
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); } }
构造函数(使用指定字符集
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(); }
读入到数组,特定位置和长度
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(); }
该类实质是一个对StreamDecoder的包装组合。该类基本所有功能都通过调用其底层流完成,本身代码没有什么有效信息,对该类的学习还是需要对StreamDecoder进行学习作为铺垫(也需要Reader类的学习