关闭嵌套流

发布于 2024-11-18 20:11:28 字数 479 浏览 6 评论 0原文

可能的重复:
关闭 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

蓝眼睛不忧郁 2024-11-25 20:11:28

关闭链式流时,只需关闭最外层的流即可。任何错误都会沿着链向上传播并被捕获。

请查看此处。可能这个问题以前已经被问过。

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.

╰つ倒转 2024-11-25 20:11:28

始终使用finally 块关闭资源:

acquire();
try {
    use();
} finally {
    release();
}

这里唯一的资源是FileOutputStream,因此它是唯一真正需要关闭的资源。如果 PrintWriter 构造函数抛出异常,您确实应该释放 FileOutputStream ,这样就无法关闭 PrintWriter

请注意,您确实想要刷新 PrintWriter。这仅需要在非异常情况下完成,因此不需要finally。

Always close resources with a finally block:

acquire();
try {
    use();
} finally {
    release();
}

Your only resource here is the FileOutputStream, so it's the only one which really needs to be closed. If the PrintWriter constructor was to throw, you really should release the FileOutputStream anyway, which precludes just closing the PrintWriter.

Note, you really do want to flush the PrintWriter. This only needs to be done in the non-exception case so doesn't need a finally.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文