InputStreamReader 源码分析

[color=violet]InputStreamReader[/color]在[color=violet]字节流[/color]和[color=violet]字符流[/color]之间架起了桥梁。能够读取字节数组并使用指定的字符集解码成字符流。

每次调用[color=violet]InputStreamReader[/color]的read方法会从底层字节流读取一个或多个字节。为了确保有效的转换,可能会从底层流中读取更多的字节。

为了提高性能,可以考虑结合[color=violet]BufferedReader[/color]使用:
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();
}
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值