Reputation: 23
I'm revising some code for a Java program written by another programmer and I'm wondering what would be the difference in wrapping an InputStreamReader
in BufferedReader
vs making a InputStreamReader
object then making a new BuffererReader
object on top of that. For example, what is the benefit of this
FileInputStream localFileInputStream = null;
localFileInputStream = new FileInputStream(someFile);
InputStreamReader localInputStreamReader = new InputStreamReader(localFileInputStream);
BufferedReader localBufferedReader = new BufferedReader(localInputStreamReader);
// Do some file processing
localFileInputStream.close();
localInputStreamReader.close();
localBufferedReader.close();
vs
FileInputStream localFileInputStream = null;
localFileInputStream = new FileInputStream(someFile);
BufferedReader localBufferedReader = new BufferedReader(new InputStreamReader(localFileInputStream));
// Do some file processing
localFileInputStream.close();
localBufferedReader.close();
In the first block of code I call localInputStreamReader.close();
but in the second block I don't (don't know how I would). Would this make any difference?
Upvotes: 1
Views: 1099
Reputation: 1856
It is worth mentioning that
BufferedReader localBufferedReader = new BufferedReader(
new InputStreamReader(new FileInputStream(someFile)));
// Do some file processing
localBufferedReader.close();
is sufficient. with Java 7 and up, you use try-with-resources to not forget closing it:
try(BufferedReader localBufferedReader = new BufferedReader(
new InputStreamReader(new FileInputStream(someFile)))) {
// Do some file processing
}
Note that the API of java.io.Closeable (which all your Readers and InputStreams implement) says:
Closes this stream and releases any system resources associated with it.
So the spec requires compliant implementations to actually delegate the close call to all wrapped resources.
Upvotes: 1
Reputation: 93
From the Java docs (BufferedReader):
close
public void throws IOException
Description copied from class: Reader
Closes the stream and releases any > system resources associated with it. Once the stream has been closed, further read(), ready(), mark(), reset(), or skip() invocations will throw an IOException. Closing a previously closed stream has no effect.
Specified by: close in interface Closeable Specified by: close in interface AutoCloseable
Specified by: close in class Reader
Throws: IOException - If an I/O error occurs
Calling close() on the BufferedReader closes the underlying stream by default implementation, since it's specified in the superclass Reader. So both of your code snippets actually do the same. Sure if there would be no such specification, or you would use your own writer and forget to close your given stream, it will have some effect. For example not closing a FileInputStream makes the underlying File inaccessible or at least unwritable.
Upvotes: 3