简体   繁体   中英

a question about closing a stream/socket in java

when does the methods socket.close() and someStream.close() throws 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. It is quite possible that errors on a previous write(2) operation are first reported at the final close(). 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.

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

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. 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. 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.

  • 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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