Reader和inputStream组合使用,但有需要各自调用自身的关闭close

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;
            }
        }
    }
 
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值