Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
188 views
in Technique[技术] by (71.8m points)

java - Do I need to close InputStream after I close the Reader

I was wondering, whether is there any need for me to close the InputStream, after I close the reader?

    try {
        inputStream = new java.io.FileInputStream(file);
        reader = new InputStreamReader(inputStream, Charset.forName("UTF-8"));
    }
    catch (Exception exp) {
        log.error(null, exp);
    }
    finally {
        if (false == close(reader)) {
            return null;
        }
        // Do I need to close inputStream as well?
        if (false == close(inputStream)) {
            return null;
        }
    }
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

No, you don't have to.

Since the decorator approach used for streams in Java can build up new streams or reader by attaching them on others this will be automatically be handled by InputStreamReader implementation.

If you look at its source InputStreamReader.java you see that:

private final StreamDecoder sd;

public InputStreamReader(InputStream in) {
  ...
  sd = StreamDecoder.forInputStreamReader(in, this, (String)null);
  ...
}

public void close() throws IOException {
  sd.close();
}

So the close operation actually closes the InputStream underlying the stream reader.

EDIT: I wanna be sure that StreamDecoder close works also on input stream, stay tuned.

Checked it, in StreamDecoder.java

void implClose() throws IOException {
  if (ch != null)
    ch.close();
  else
    in.close();
}

which is called when sd's close is called.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...