Do I need to close InputStream after I close the Reader

前端 未结 5 995
面向向阳花
面向向阳花 2020-12-05 16:50

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

    try {
        inputStream = new java.io.FileInputSt         


        
5条回答
  •  广开言路
    2020-12-05 17:41

    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.

提交回复
热议问题