Should BufferedReader and InputStreamReader be closed explicitly?

ε祈祈猫儿з 提交于 2019-12-08 02:09:31

问题


I want to read the content of a InputStream into a String:

private String readToString(InputStream stream) {
    return new BufferedReader(new InputStreamReader(stream))
            .lines().collect(Collectors.joining("\n"));
}

The stream comes from java.lang.Process.

Question: Do I have to explicitly close any of the InputStream, InputStreamReader or BufferedReader in this case?

Sidenote: the linked question is NOT a duplicate, as my question is about HOW to properly close the streams, not how to read the stream to a String!


回答1:


You only need to close the outer wrapper, but don't do that explicitly either way - there is try-with-resource that will make your life easier:

public String readToString(InputStream stream) {

    try (InputStreamReader reader = new InputStreamReader(stream);
            BufferedReader br = new BufferedReader(reader)) {

        return br.lines().collect(Collectors.joining("\n"));

    } catch (IOException e) {
        e.printStackTrace();
        throw new RuntimeException(e);
    }
}

There is also a much easier way to do that and way more clear:

Files.readAllLines(YourPath)



回答2:


As per my comment, closing either the BufferedReader or the InputStreamReader will cause the InputStream to be closed. Your readToString method should not close the stream. This is the responsibility of the caller.

The rationale:-

Firstly, consider how you open the stream before you call readToString. A sensible way to do it is:

try (InputStream myStream = getInputStreamSomehow()) {
    //...
    String content = readToString(myStream);
    //...
}

The stream will be closed at the end of your try-with-resources block.

Secondly, consider existing best practices and idioms. Look at Java API methods that, just like your method, read the whole contents of a stream. For example, from Java 9:

  • readAllBytes()
  • transferTo(OutputStream out)

Neither of the above methods closes the stream. Similarly, the users of your readToString method will not be expecting you to close their stream.



来源:https://stackoverflow.com/questions/47347575/should-bufferedreader-and-inputstreamreader-be-closed-explicitly

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!