1

考虑这段代码:

    FileOutputStream stream=null;
    ObjectOutputStream objStr=null;
    try
    {
        stream=new FileOutputStream(defaultFile);
        objStr=new ObjectOutputStream(stream);
        objStr.writeObject(obj);
        objStr.close();
    }
    catch(FileNotFoundException e)
    {
        System.out.println("Il file "+ defaultFile+ " non è stato trovato\n");
    }
    catch(IOException e)
    {
        stream.close();
        System.out.println("Si è verificato un problema di I/O nell' apertura dello  stream");
    }

在第二个 catch 块中,我关闭了流,但我不确定是否应该关闭它。
如果 ObjectOutputStream 的构造函数失败,它将进入第二个捕获,但我确定在这种情况下,FileOutputStream 保持打开状态吗?
我应该写一个 finally 块来处理所有异常吗?
我很难弄清楚所有情况。

4

3 回答 3

4

如果您使用的是 Java 7,则可以使用try-with-resources语句为您处理所有关闭操作。

try(ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream(defaultFile))) {
    oos.writeObject(obj);
} catch (IOException e) {
    e.printStackTrace();
}
于 2012-03-31T14:33:02.617 回答
2

将 finally 块添加到您的 try-catch 语句并在那里进行关闭。为了避免另一个 try-catch 和 nullcheck 在那里你可以使用 commons.io IOUtils.closeQuietly()

    FileOutputStream stream = null;
    ObjectOutputStream objStr = null;
    try {
        stream = new FileOutputStream(defaultFile);
        objStr = new ObjectOutputStream(stream);
        objStr.writeObject(obj);
    } catch (FileNotFoundException e) {
        System.out.println("Il file " + defaultFile + " non è stato trovato\n");
    } catch (IOException e) {
        System.out.println("Si è verificato un problema di I/O nell' apertura dello  stream");
    } finally {
        IOUtils.closeQuietly(stream);
        IOUtils.closeQuietly(objStr);
    }      
于 2012-03-31T14:41:22.893 回答
1

您可以在关闭流之前添加一个 if 条件,如下所示

if(stream != null) {
    stream.close();
}
于 2012-03-31T14:35:02.857 回答