When we need close an output stream, we have two choices.
closeQuietly means close a stream with no exception throwing up.
try {
close(out)
} catch(IOException e) {
}
close
try {
close(out)
} catch(IOException e) {
throw anException;
}
as known, output stream will write a/several chars into the end of file when closing, if these writing goes wrong, the file also can't be open correctly such as ZipoutputStream.
if I use the first one, I will get some risk of fail closing. if I use the second one, it will let my code unfriendly.
Could someone give me some advices?
So sorry for describing the issue unclearly.
I meant that how to get an IO operation safely. if a resource's release gets failed, it would let caller know.
Thanks for all your answer. And especially thank @Don Roby for giving me a link which contains the best answer answered by @Fabian Barney
close() method closes this output stream and releases any system resources associated with this stream. The general contract of close is that it closes the output stream. A closed stream cannot perform output operations and cannot be reopened.
No. It is not require to close other components.
void close() It is used to closes the file output stream.
OutputStream , say FileOutputStream , after writing to a file, if we don't close() the output stream, the data that we intended to write in the file remains in the buffer and is not written to the file. So it becomes necessary to close() an OutputStream .
Since Java 7 IOUtils.closeQuietly
became outdated and the only reasonable solution is try-with-resources
which closes resources automatically
try (InputStream is = new FileInputStream(file)) {
...
}
Note that it also solves problem with correctly opening / closing more than one resource
try (InputStream is = new FileInputStream(infile); OutputStream out = new FileOutputStream(outfile)) {
...
}
And it also does not suppress IOException that close()
may throw, which is exactly what closeQuietly
does.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With