|
|
InputStreamReader在字节流和字符流之间架起了桥梁。能够读取字节数组并使用指定的字符集解码成字符流。
每次调用InputStreamReader的read方法会从底层字节流读取一个或多个字节。为了确保有效的转换,可能会从底层流中读取更多的字节。
为了提高性能,可以考虑结合BufferedReader使用:
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
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); } } // 根据指定的字符集名来创建实例 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(); } // 关闭Reader public void close() throws IOException { sd.close(); }} |
|