Should I use method close or closeQuietly to close an output stream?

Mr rain picture Mr rain · Jun 4, 2013 · Viewed 10.1k times · Source

When we need close an output stream, we have two choices.

  1. closeQuietly means close a stream with no exception throwing up.

    try {
        close(out)
    } catch(IOException e) {
    }
    
  2. 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

Answer

Evgeniy Dorofeev picture Evgeniy Dorofeev · Jun 4, 2013

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.