Should BufferedReader and InputStreamReader be closed explicitly?

流过昼夜 提交于 2019-12-06 10:00:18

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)

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:

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

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