I will be performing a lecture on Java for students of Physics, and I would like to know how to properly open a file.
In many my proffesional apps I did somethings like that:
BufferedWriter bufferedWriter = new BufferedWriter(new OutputStreamWriter(new FileOutputStream("file")));
try{
....
}finally {
bufferedWriter.close();
}
which is IMHO ok, i.e. reader will allways be closed.
When I was putting that in example for my students I was wondering what will happen if constructor of InputStreamReader will throw an exception --- FileInputStream will be open, but it will not be closed by my code (since these objects are created outside try-finally block.
So is this right idiom, and if so then why? If it is not right idiom to open a stream please point me the right one!
Edit: I'm looking for idiom that is both correct and very easy to write and understand, physics students are beginners in programming.
Edit: Silly me I copied wrong example --- if instead of Readers I use Writers it get's more complicated.
Prior to Java 7 this is how you'd do it
InputStream in = null;
try {
in = new FileInputStream("simple.csv");
BufferedReader buf = new BufferedReader(new InputStreamReader(in));
} finally {
if (in != null) {
try {
in.close();
} catch (IOException e) {}
}
}
For Java 7 you can use Closeable, something like
try (BufferedReader buf = new BufferedReader(...)) {}
EDIT: Why didn't I close buf above? Have a look at the source code for BufferedReader.close()
public void close() throws IOException {
synchronized (lock) {
if (in == null)
return;
in.close();
in = null;
cb = null;
}
}
EDIT 2: The same principle applies to writers. However if you're really interested in flushing a stream when the IOException occurs, then you must check both the writer and the stream for null and try tro close them respectively. That though, gives a lot of extra code. It could look something like this:
BufferedWriter buf = null;
OutputStream out = null;
try {
out = new FileOutputStream("file");
buf = new BufferedWriter(new OutputStreamWriter(out));
} finally {
if (buf != null) {
try { buf.close(); } catch (IOException ex){}
}
if (out != null) {
try { out.close(); } catch (IOException ex){}
}
}
It's not very pretty. You could introduce a helper routine to close your streams or look into either Java 7 or Apache IOUtils
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With