Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Do I need to close() both FileReader and BufferedReader?

People also ask

Do we need to close BufferedReader?

When you are finished reading characters from the BufferedReader you should remember to close it. Closing a BufferedReader will also close the Reader instance from which the BufferedReader is reading.

What happens if you don't close a BufferedReader?

Closes this stream and releases any system resources associated with it. If the stream is already closed then invoking this method has no effect. So, if you don't close(), system resources may be still associated with the reader which may cause memory leak.

How do I close a BufferedReader?

The close() method of BufferedReader class in Java is used to close the stream and release all the system resources associated with the stream operations. Parameters: This method does not accept any parameter. Return value: This method does not return any value.

What is the difference between FileReader and BufferedReader?

FileReader is used to read a file from a disk drive whereas BufferedReader is not bound to only reading files. It can be used to read data from any character stream.


no.

BufferedReader.close()

closes the stream according to javadoc for BufferedReader and InputStreamReader

as well as

FileReader.close()

does.


As others have pointed out, you only need to close the outer wrapper.

BufferedReader reader = new BufferedReader(new FileReader(fileName));

There is a very slim chance that this could leak a file handle if the BufferedReader constructor threw an exception (e.g. OutOfMemoryError). If your app is in this state, how careful your clean up needs to be might depend on how critical it is that you don't deprive the OS of resources it might want to allocate to other programs.

The Closeable interface can be used if a wrapper constructor is likely to fail in Java 5 or 6:

Reader reader = new FileReader(fileName);
Closeable resource = reader;
try {
  BufferedReader buffered = new BufferedReader(reader);
  resource = buffered;
  // TODO: input
} finally {
  resource.close();
}

Java 7 code should use the try-with-resources pattern:

try (Reader reader = new FileReader(fileName);
    BufferedReader buffered = new BufferedReader(reader)) {
  // TODO: input
}

The source code for BufferedReader shows that the underlying is closed when you close the BufferedReader.


According to BufferedReader source, in this case bReader.close call fReader.close so technically you do not have to call the latter.