Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

java file handling and exceptions

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?

like image 792
Rene Avatar asked Dec 03 '22 09:12

Rene


1 Answers

use apache commons io

http://commons.apache.org/proper/commons-io/

look at their FileUtils class. Full of gold. Gold I say....

like image 191
hvgotcodes Avatar answered Dec 05 '22 23:12

hvgotcodes