While working on a school project, I wrote the following code:
FileOutputStream fos;
ObjectOutputStream oos;
try {
fos = new FileOutputStream(file);
Current best practice for try/catch/finally involving objects that are closeable (e.g. Files) is to use Java 7's try-with-resource statement, e.g.:
try (FileReader reader = new FileReader("ex.txt")) {
System.out.println((char)reader.read());
} catch (IOException ioe) {
ioe.printStackTrace();
}
In this case, the FileReader is automatically closed at the end of the try statement, without the need to close it in an explicit finally block. There are a few examples here:
http://ppkwok.blogspot.com/2012/11/java-cafe-2-try-with-resources.html
The official Java description is at:
http://docs.oracle.com/javase/7/docs/technotes/guides/language/try-with-resources.html