简体   繁体   English

关于在java中关闭流/套接字的问题

[英]a question about closing a stream/socket in java

when does the methods socket.close() and someStream.close() throws IOException? 方法socket.close()和someStream.close()何时抛出IOException? and how can I solve the problem? 我该如何解决这个问题?

thanks benny. 谢谢你好。

Not checking the return value of close() is a common but nevertheless serious programming error. 不检查close()的返回值是一个常见但严重的编程错误。 It is quite possible that errors on a previous write(2) operation are first reported at the final close(). 很可能首先在最后的close()上报告先前write(2)操作的错误。 Not checking the return value when closing the file may lead to silent loss of data. 关闭文件时不检查返回值可能会导致数据无声丢失。 This can especially be observed with NFS and with disk quota. 使用NFS和磁盘配额尤其可以观察到这种情况。

While closing a readonly stream can't throw, java's IO framework can't check for that as it doesn't have statically checked read vs. write streams 虽然关闭一个readonly流不能抛出,但是java的IO框架无法检查它,因为它没有静态检查的读取与写入流

What you should do really depends on your application. 你应该做什么取决于你的应用程序。 For example, if it is a GUI application and the user tried to save a file, you probably want to notify the user and give her a chance to save the file somewhere else. 例如,如果它是GUI应用程序并且用户试图保存文件,您可能希望通知用户并让她有机会将文件保存在其他位置。 Sometimes it may also make sense to try again to execute the operating a second time before reporting an error to the user. 有时,在向用户报告错误之前再次尝试执行操作也是有意义的。 Otherwise, report an error and either move on or abort the program, depending on whether it makes sense to continue or not. 否则,报告错误并继续或中止程序,具体取决于是否继续。

This SO question discusses the situations in which close() may throw an exception. 这个SO问题讨论了close()可能引发异常的情况。 Actually, there are quite a few of them. 实际上,他们中有不少人。

Generally speaking there is not much you can do to fix the problem. 一般来说,你无法解决问题。 However you may need to take some recovery action. 但是,您可能需要采取一些恢复措施。 For example: 例如:

  • If you were writing a critical file, and the close() failed, then your application should take steps to ensure that it doesn't clobber the "good" copy of the file with the new copy of file it was writing. 如果您正在编写关键文件,并且close()失败,那么您的应用程序应该采取措施确保它不会使用它正在编写的新文件副本来破坏文件的“正常”副本。

  • If you were writing a request or response using a network socket, maybe you should note that the request/response may not have been sent, so that you can resend it after the connection has been re-established. 如果您使用网络套接字编写请求或响应,可能应注意可能尚未发送请求/响应,因此您可以在重新建立连接后重新发送请求/响应。

Of course it is generally a good idea to report / log the "failure" as well. 当然,报告/记录“失败”通常也是一个好主意。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM