简体   繁体   English

仅在流打开时关闭它

[英]Closing the stream only if it's opened

Consider this code: 考虑以下代码:

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

In the second catch block, I close the stream but I am not sure if it should be closed. 在第二个catch块中,我关闭了流,但是不确定是否应该将其关闭。
It enters in the second catch if the constructor of ObjectOutputStream fails, but am I sure that in this case, the FileOutputStream remains opened? 如果ObjectOutputStream的构造函数失败,它将进入第二个捕获,但是我确定在这种情况下FileOutputStream保持打开状态吗?
Shall I write a finally block to handle all exceptions? 我应该写一个finally块来处理所有异常吗?
It's hard for me to figure out all cases. 我很难弄清所有情况。

If you are using Java 7, you can use the try-with-resources statement to handle all of the closing for you. 如果您使用的是Java 7,则可以使用try-with-resources语句为您处理所有结帐。

try(ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream(defaultFile))) {
    oos.writeObject(obj);
} catch (IOException e) {
    e.printStackTrace();
}

Add a finally block to your try-catch statement and do the closing there. 在您的try-catch语句中添加一个finally块,然后在此结束。 To avoid another try-catch and a nullcheck in there you can use commons.io IOUtils.closeQuietly() : 为了避免在那里再次尝试捕获和进行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);
    }      

You could add an if condition before closing the stream as follows 您可以在关闭流之前添加if条件,如下所示

if(stream != null) {
    stream.close();
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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