六狼论坛

 找回密码
 立即注册

QQ登录

只需一步,快速开始

新浪微博账号登陆

只需一步,快速开始

搜索
查看: 12|回复: 0

InputStreamReader 源码分析

[复制链接]

升级  37.4%

217

主题

217

主题

217

主题

进士

Rank: 4

积分
687
 楼主| 发表于 2013-2-3 10:36:41 | 显示全部楼层 |阅读模式
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();  }}
您需要登录后才可以回帖 登录 | 立即注册 新浪微博账号登陆

本版积分规则

快速回复 返回顶部 返回列表