简体   繁体   中英

Java - close multi-layer stream wrapper

In Java, we usually use a stream object to wrap another stream class for efficiency. For example:

Object obj = new MyClass();
try {
    FileOutputStream fos = new FileOutputStream("test.txt");
    ObjectOutputStream oos = new ObjectOutputStream(fos);

   oos.writeObject(obj);
   oos.flush();
} catch(IOException e) {
    e.printStackTrace();
} finally {
    fos.close();
    oos.close();
}

I use ObjectOutputStream to wrap FileOutputStream . A similar case is using BufferedReader to wrap InputStreamReader .

My question is how to close the fos and oos properly in order. Which one should be closed first? Or just need to close either one. Usually closing both streams will work, but I feel uncomfortable with this way since I don't understand the semantics. I just use the close method to close everything, while I don't know why not just close fos or oos .

Closing the wrapper stream automatically closes the inner stream.

So, in your case you only need to close ObjectOutputStream . Closing a stream twice does not throw an exception hence what you've already been doing (although unnecessary) works as well.

Here's what happens when you instantiate an ObjectOutputStream

public ObjectOutputStream(OutputStream out) throws IOException {
    bout = new BlockDataOutputStream(out); // inner stream being wrapped
    ...
}

Here's the implementation of ObjectOutputStream.close()

public void close() throws IOException {
    flush();
    clear();
    bout.close(); // inner stream being closed
}

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