开发者

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 I开发者_运维百科NSIDE 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....


This is not the standard way at all. This is the bad way.

The way I use most of the time is this one :

ObjectOutputStream out = null;
try {
    out = new ObjectOutputStream(new FileOutputStream("file.dat"));
    // use out
}
finally {
    if (out != null) {
        try {
            out.close();
        }
        catch (IOException e) {
            // nothing to do here except log the exception
        }
    }
}

The code in the finally block can be put in a helper method, or you can use commons IO to close the stream quietly, as noted in other answers.

A stream must always be closed in a finally block.

Note that JDK7 will make it much easier with the new syntax, which will automatically close the stream at the end of the try block :

try (ObjectOutputStream out = new ObjectOutputStream(new FileOutputStream("file.dat"))) {
    // use out
}


This why I use commons-io's IOUtils.closeQuitely(...)

try
{
...
}
finally 
{
   IOUtils.closeQuietly(costream);
}


try
{
    ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream("file.dat"));
    oos.writeObject(h);
    //oos.close(); // glow coder removed
}
catch (FileNotFoundException ex)
{
}
catch (IOException ex)
{
}
// glowcoder adds:
finally {
    try {
        oos.close();
    }
    catch(IOException ex) {
        // dammit we tried!
    }
}


add this finally:

finally{
   if(oos != null)
      oos.close();
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜