The standard way of handling file reading and writing in java goes something like this:
try
{
ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream("file.dat"));
oos.writeObject(h);
oos.close();
}
catch (FileNotFoundException ex)
{
}
catch (IOException ex)
{
}
But I'm bothered by that code, because it could be possible here that the file is never closed if an exception is thrown. Sure we could add a finally clause and initialise the ObjectOutputStream outside the try block. However, when you do that you need to add another try/catch block INSIDE the finally block again...that's just ugly. Is there a better way of handling this problem?
use apache commons io
http://commons.apache.org/proper/commons-io/
look at their FileUtils class. Full of gold. Gold I say....
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