简体   繁体   中英

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.
It enters in the second catch if the constructor of ObjectOutputStream fails, but am I sure that in this case, the FileOutputStream remains opened?
Shall I write a finally block to handle all exceptions?
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.

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. To avoid another try-catch and a nullcheck in there you can use 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(stream != null) {
    stream.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