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.