Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Should I always close BufferedReader?

Here is a line reading a file into a List:

List<String> lines =
    new BufferedReader(
        new InputStreamReader(classLoader.getResourceAsStream(fileName)))
            .lines()
            .collect(Collectors.toList());

Is this correct or should I assign the BufferedReader to a variable to be able to close it later?

like image 965
Ekaterina Avatar asked Feb 26 '19 15:02

Ekaterina


2 Answers

You should always close your resources. Closing may not be a big problem for small programs which only use a couple of files quickly, since most mature OSes will close the files for you when the process completes. However, there are usually limits on how many files you can have open at one time. It is good to be tidy, so that you don't hit those limits when you start writing bigger programs. There are also other types of resources, like network and serial ports, which you may want to let others use once your program is done with them, even if it is still running.

An alternative to closing the file manually is using try-with-resources syntax, which ensures that the file will be closed properly even in case of an error:

List<String> lines;
try(BufferedReader reader = new BufferedReader(
        new InputStreamReader(classLoader.getResourceAsStream(fileName)))) {
    lines = reader.lines().collect(Collectors.toList());
}
like image 165
Mad Physicist Avatar answered Nov 16 '22 23:11

Mad Physicist


Well, in your concrete example, the stream opened by

classLoader.getResourceAsStream(fileName)

is never closed. This stream must be closed - it is most likely a file handle in the local system. You can close it by closing the BufferedReader, which closes the wrapped InputStreamReader, which closes the underlying InputStream. You could instead also store a reference to the original InputStream and only close this.

Please also have a look into try-with-resources, this could potentially make things easier for you here.

like image 6
Florian Albrecht Avatar answered Nov 16 '22 22:11

Florian Albrecht