【发布时间】:2013-05-16 03:51:48
【问题描述】:
在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();
}
我使用ObjectOutputStream 包裹FileOutputStream。类似的情况是使用BufferedReader 包裹InputStreamReader。
我的问题是如何按顺序正确关闭fos 和oos。应该先关闭哪个?或者只需要关闭其中一个。
通常关闭两个流都会起作用,但我对这种方式感到不舒服,因为我不理解语义。我只是使用close方法关闭所有东西,而我不知道为什么不直接关闭fos或oos。
【问题讨论】: