Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Closing nested Reader

When reading from a text file, one typically creates a FileReader and then nests that in a BufferedReader. Which of the two readers should I close when I'm done reading? Does it matter?

FileReader fr = null;
BufferedReader br = null;
try
{
    fr = new FileReader(fileName);
    br = new BufferedReader(fr);
    // ...
}
finally
{
    // should I close fr or br here?
}

I'm a little paranoid when it comes to exception-safety. What happens when the BufferedReader constructor throws an exception? Does it close the nested reader? Or is it guaranteed not to throw?

like image 274
fredoverflow Avatar asked Feb 05 '11 19:02

fredoverflow


People also ask

What is the use of the close method of reader class?

The close () method of Reader Class in Java is used to close the stream and release the resources that were busy in the stream, if any. This method has following results: If the stream is already closed, it will have no effect. If any read or other similar operation is performed on the stream, after closing, it raises IOException Attention reader!

What is the use of close() method of BufferedReader in Java?

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.

What does the method close do in a streamwriter?

This implementation of Close calls the Dispose method, passing a true value. Following a call to Close, any operations on the reader might raise exceptions. Reads the lines of a file. Closes the current StreamWriter object and the underlying stream. Implements a TextWriter for writing characters to a stream in a particular encoding.

What is the use of close () method in Java?

The close () method of Reader Class in Java is used to close the stream and release the resources that were busy in the stream, if any. This method has following results: If the stream is open, it closes the stream releasing the resources If the stream is already closed, it will have no effect.


1 Answers

Generally, close() on the outermost stream wrapper will call close() on the wrapped streams. However, if you think it's likely that a constructor will throw an exception, make liberal use of the Closeable interface.

FileReader fr = new FileReader(fileName);
Closeable res = fr;
try {
    BufferedReader br = new BufferedReader(fr);
    res = br;
} finally {
    res.close();
}

So, even if the JVM ran out of heap space for the buffer and threw an error, you wouldn't leak a file handle.

For Java 7 and above use try-with-resources:

try (FileReader fr = new FileReader(fileName);
    BufferedReader br = new BufferedReader(fr)) {
  // do work
}
like image 111
McDowell Avatar answered Sep 27 '22 23:09

McDowell