Close a BufferedReader

2

My question is whether it is strictly mandatory to close a BufferedReader with .close() .

I am practicing with reading and writing files and, for example, if a BufferedWriter does not close it with .close() it does not do anything, therefore it is mandatory to close it.

The same thing happens with BufferedReader , that is, it is strictly obligatory to close it? Or can it be left unlocked? Is there any problem?

    
asked by Sergio AG 19.04.2018 в 15:44
source

1 answer

4

It is not strictly mandatory to close the BufferedReader, but it is a good practice to do it, since when closing a BufferedReader you are releasing resources that you no longer need. What happens if you leave BufferedReader without closing because your application may have problems with memory and performance.

So the advice I give you is to close all the BufferedReader and BufferedWriter that you no longer need.

I do not know what version of java you are using, but from Java 7 you can do that:

try (BufferedReader buffer = new BufferedReader(new FileReader("test.txt"))){
    String linea;
    while ((linea = buffer.readLine()) != null) {
        System.out.println(linea);
    }
} catch (IOException e) {
    e.printStackTrace();
}  

This is called try-with-resources what has been declared within the statement try will be automatically closed when the block of statements that are in try are fully executed .

    
answered by 19.04.2018 / 16:00
source