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.
Reading with input streams
Prior to Java 7 this is how you’d do it
For Java 7 you can use
Closeable, something likeEDIT: Why didn’t I close
bufabove? Have a look at the source code forBufferedReader.close()Writing with output streams
EDIT 2: The same principle applies to writers. However if you’re really interested in flushing a stream when the
IOExceptionoccurs, then you must check both thewriterand thestreamfornulland try tro close them respectively. That though, gives a lot of extra code. It could look something like this:It’s not very pretty. You could introduce a helper routine to close your streams or look into either Java 7 or
Apache IOUtils