Java-关闭多层流包装器

Zac*_*ary 5 java stream

在Java中,我们通常使用一个流对象来包装另一个流类以提高效率。例如:

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();
}
Run Code Online (Sandbox Code Playgroud)

我用来ObjectOutputStream包裹FileOutputStream。类似的情况是使用BufferedReader包装InputStreamReader

我的问题是如何按顺序正确关闭fosoos。应该先关闭哪一个?或者只需要关闭其中一个。通常关闭两个流都会起作用,但我对这种方式感到不舒服,因为我不理解语义。我只是使用 close 方法来关闭所有内容,而我不知道为什么不直接 closefosoos

Rav*_*yal 5

关闭包装器流会自动关闭内部流。

所以,在你的情况下,你只需要关闭ObjectOutputStream. 关闭流两次不会引发异常,因此您已经在做的事情(尽管不必要)也有效。

这是实例化时会发生的情况ObjectOutputStream

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

这是执行ObjectOutputStream.close()

public void close() throws IOException {
    flush();
    clear();
    bout.close(); // inner stream being closed
}
Run Code Online (Sandbox Code Playgroud)