Reader下的子类,使用组合的方式封装了inputStream对象。
private final StreamDecoder sd;
/**
* Creates an InputStreamReader that uses the default charset.
*
* @param in An InputStream
*/
public InputStreamReader(InputStream in) {
super(in);
sd = StreamDecoder.forInputStreamReader(in, this,
Charset.defaultCharset()); // ## check lock object
}
基类Reader是将传入的InputStream作为同步锁使用,即:
protected Object lock;
protected Reader(Object lock) {
if (lock == null) {
throw new NullPointerException();
}
this.lock = lock;
}
//这段描述是关于Java中的Reader类中的skip(long n)方法的说明。
//该方法用于跳过输入流中的字符。它会阻塞当前线程,直到有字符可用、发生I/O错误或达到流的末尾。
//方法的参数是n,表示要跳过的字符数。
//方法的返回值是实际跳过的字符数。
//如果传入的n是负数,则会抛出IllegalArgumentException异常。
//如果在跳过字符的过程中发生I/O错误,则会抛出IOException异常。
public long skip(long n) throws IOException {
if (n < 0L)
throw new IllegalArgumentException("skip value is negative");
int nn = (int) Math.min(n, maxSkipBufferSize);
synchronized (lock) {
if ((skipBuffer == null) || (skipBuffer.length < nn))
skipBuffer = new char[nn];
long r = n;
while (r > 0) {
int nc = read(skipBuffer, 0, (int)Math.min(r, nn));
if (nc == -1)
break;
r -= nc;
}
return n - r;
}
}
但是关闭close方法中并没有一起关闭InputStream,即只调用Reader自身的close方法。
public void close() throws IOException {
//这里的sd,就是构造创建的StreamDecoder
sd.close();
}
一般使用Reader时会配合BufferedReader一起使用,而BufferReader也是直接关闭封装的Reader,所以仍然需要额外手动关闭InputStream:
public class BufferedReader extends Reader {
private Reader in;
//................
public BufferedReader(Reader in, int sz) {
super(in);
if (sz <= 0)
throw new IllegalArgumentException("Buffer size <= 0");
this.in = in;
cb = new char[sz];
nextChar = nChars = 0;
}
public BufferedReader(Reader in) {
this(in, defaultCharBufferSize);
}
//.........................
public void close() throws IOException {
//只是处理了Reader的关闭
synchronized (lock) {
if (in == null)
return;
try {
in.close();
} finally {
in = null;
cb = null;
}
}
}
}