Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it safe to use Apache commons-io IOUtils.closeQuietly?

Is this code

    BufferedWriter bw = new BufferedWriter(new FileWriter("test.txt"));     try {         bw.write("test");     } finally {         IOUtils.closeQuietly(bw);     } 

safe or not? As far as I understand when we close a BufferedWriter it will flush its buffer to the underlying stream and may fail due to an error. But IOUtils.closeQuietly API says that any exceptions will be ignored.

Is it possible a data loss will go unnoticed due to IOUtils.closeQuietly?

like image 403
Evgeniy Dorofeev Avatar asked Jan 21 '13 10:01

Evgeniy Dorofeev


People also ask

Is Apache commons safe?

Yes, it's safe to use it but only for Java6 and lower. From Java7, you should user try-with-resource. It will eliminate much of the boilerplate code you have and the need to use IOUtils.

What is org Apache Commons IO IOUtils?

IOUtils provide utility methods for reading, writing and copying files. The methods work with InputStream, OutputStream, Reader and Writer.

What does IOUtils copy do?

Copies chars from a Reader to bytes on an OutputStream using the specified character encoding, and calling flush.

Does IOUtils copy close the stream?

Applications can re-use buffers by using the underlying methods directly. This may improve performance for applications that need to do a lot of copying. Wherever possible, the methods in this class do not flush or close the stream.


Video Answer


1 Answers

The code should look like this regarding to the javadoc of closeQuietly():

BufferedWriter bw = null;  try {     bw = new BufferedWriter(new FileWriter("test.txt"));     bw.write("test");     bw.flush(); // you can omit this if you don't care about errors while flushing     bw.close(); // you can omit this if you don't care about errors while closing } catch (IOException e) {     // error handling (e.g. on flushing) } finally {     IOUtils.closeQuietly(bw); } 

closeQuietly() is not intended for general use instead of calling close() directly on a Closable. Its intended use-case is for ensuring the close inside a finally-block - all error handling you need have to be done BEFORE that.

That means, if you want to react on Exceptions during the call of close() or flush() then you've to handle it the normal way. Adding closeQuietly() in your finally-block just ensures the close, e.g. when the flush failed and close was not called in try-block.

like image 190
Fabian Barney Avatar answered Sep 30 '22 18:09

Fabian Barney