简体   繁体   中英

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?

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();
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM