Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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

like image 363
Mr rain Avatar asked Jun 04 '13 10:06

Mr rain


People also ask

How do I close an output stream?

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.

Do I need to close output stream?

No. It is not require to close other components.

Is used to close the current output stream?

void close() It is used to closes the file output stream.

Why is it important to close the Fileinputstream and FileOutputStream after we are done processing the file?

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 .


1 Answers

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.

like image 83
Evgeniy Dorofeev Avatar answered Sep 19 '22 15:09

Evgeniy Dorofeev