InputStreamReader 是字节流通向字符流的桥梁:它使用指定的 charset 读取字节并将其解码为字符。它使用的字符集可以由名称指定或显式给定,或者可以接受平台默认的字符集。
OutputStreamWriter 是字符流通向字节流的桥梁:可使用指定的 charset 将要写入流中的字符编码成字节。它使用的字符集可以由名称指定或显式给定,否则将接受平台默认的字符集。
InputStreamReader 及其子类 FileReader:(从字节到字符)是个解码过程。
OutputStreamWriter 及其子类 FileWriter:(从字符到字节)是个编码过程。
InputStreamReader 的方法,其实都是交给 StreamDecoder 来进行处理的。
OutputStreamWriter 的方法,其实都是交给 StreamEncoder 来进行处理的。
在使用时,在编码和解码的过程中一定要指定字符集,否则使用操作系统默认字符集很可能出现问题。
下面以 InputStreamReader 为例,对应的 OutputStreamWriter 原理几乎一样。
InputStreamReader
属性
// 有一个从父类继承的对象锁
// 这个是一个负责解码的对象
private final StreamDecoder sd;
构造方法
// 创建一个使用默认字符集的InputStreamReader
public InputStreamReader(InputStream in) {
super(in);
try {
sd = StreamDecoder.forInputStreamReader(in, this, (String)null);
} catch (UnsupportedEncodingException e) {
// The default encoding should always be available
throw new Error(e);
}
}
// 创建使用给定字符集的InputStreamReader
public InputStreamReader(InputStream in, String charsetName)
throws UnsupportedEncodingException
{
super(in);
if (charsetName == null)
throw new NullPointerException("charsetName");
sd = StreamDecoder.forInputStreamReader(in, this, charsetName);
}
// 创建使用指定字符集的InputStreamReader
public InputStreamReader(InputStream in, Charset cs) {
super(in);
if (cs == null)
throw new NullPointerException("charset");
sd = StreamDecoder.forInputStreamReader(in, this, cs);
}
// 创建使用给定字符集解码器的InputStreamReader
public InputStreamReader(InputStream in, CharsetDecoder dec) {
super(in);
if (dec == null)
throw new NullPointerException("charset decoder");
sd = StreamDecoder.forInputStreamReader(in, this, dec);
}
方法
getEncoding()
返回此流使用的字符编码的名称。
public String getEncoding() {
return sd.getEncoding();
}
read()
读取单个字符。
public int read() throws IOException {
return sd.read();
}
read(char cbuf[], int offset, int length)
读取字符存入目标字符数组中,从 offset 下标开始共 length 个。
public int read(char cbuf[], int offset, int length) throws IOException {
return sd.read(cbuf, offset, length);
}
ready()
判断此流是否已经准备好用于读取。如果其输入缓冲区不为空,或者可从底层字节流读取字节,则 InputStreamReader 已做好被读取准备。
public boolean ready() throws IOException {
return sd.ready();
}
close()
关闭该流并释放与之关联的所有资源。在关闭该流后,再调用 read()、ready()、mark()、reset() 或 skip() 将抛出 IOException。关闭以前关闭的流无效。
public void close() throws IOException {
sd.close();
}