关闭嵌套流
可能的重复:
关闭 Java 中嵌套流的最佳方法?
我们如何关闭嵌套流?全部关闭?如果是,顺序是什么?
FileOutputStream out = new FileOutputStream("data.txt", true);
PrintWriter pout = new PrintWriter(out);
/* do some I/O */
pout.close();
out.close();
或者关闭最外的流将关闭所有流。
pout.close(); // Is this enough?
Possible Duplicate:
Best way to close nested streams in Java?
How we close nested streams? Closing all of them? If yes what is the order?
FileOutputStream out = new FileOutputStream("data.txt", true);
PrintWriter pout = new PrintWriter(out);
/* do some I/O */
pout.close();
out.close();
or closing the the out most stream will close all of them.
pout.close(); // Is this enough?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
关闭链式流时,只需关闭最外层的流即可。任何错误都会沿着链向上传播并被捕获。
请查看此处。可能这个问题以前已经被问过。
When closing chained streams, you only need to close the outermost stream. Any errors will be propagated up the chain and be caught.
Take a look at here. Probably this question has been asked before.
始终使用
finally
块关闭资源:这里唯一的资源是
FileOutputStream
,因此它是唯一真正需要关闭的资源。如果PrintWriter
构造函数抛出异常,您确实应该释放FileOutputStream
,这样就无法关闭PrintWriter
。请注意,您确实想要
刷新
PrintWriter
。这仅需要在非异常情况下完成,因此不需要finally。Always close resources with a
finally
block:Your only resource here is the
FileOutputStream
, so it's the only one which really needs to be closed. If thePrintWriter
constructor was to throw, you really should release theFileOutputStream
anyway, which precludes just closing thePrintWriter
.Note, you really do want to
flush
thePrintWriter
. This only needs to be done in the non-exception case so doesn't need a finally.