I usually do the following. First, define a template-based class to solve the try / catch mess problem
import java.io.Closeable; import java.io.IOException; import java.util.LinkedList; import java.util.List; public abstract class AutoFileCloser { private static final Closeable NEW_FILE = new Closeable() { public void close() throws IOException {
Pay attention to the âpendingâ exception - this refers to the case when the exception created at the time of closure would mask the exception, which might really bother.
Finally, it first tries to close any decorated stream from the outside, so if you have a BufferedWriter that wraps FileWriter, we first try to close the BuffereredWriter, and if that fails, try closing the FileWriter itself.
You can use the above class as follows:
try { // ... new AutoFileCloser() { @Override protected void doWork() throws Throwable { // declare variables for the readers and "watch" them FileReader fileReader = null; BufferedReader bufferedReader = null; watch(fileReader = new FileReader("somefile")); watch(bufferedReader = new BufferedReader(fileReader)); // ... do something with bufferedReader // if you need more than one reader or writer newFile(); // puts a flag in the FileWriter fileWriter = null; BufferedWriter bufferedWriter = null; watch(fileWriter = new FileWriter("someOtherFile")); watch(bufferedWriter = new BufferedWriter(fileWriter)); // ... do something with bufferedWriter } }; // .. other logic, maybe more AutoFileClosers } catch (RuntimeException e) { // report or log the exception }
Using this approach, you never have to worry about trying / tricking / finally dealing with closing files.
If this is too heavy for your use, at least think about how to use the try / catch method and the "pending" variable approach that it uses.
Scott Stanchfield Oct 08 '08 at 16:56 2008-10-08 16:56
source share