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

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


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.


It is safe so long as your application doesn't care whether the write succeeded without error. If your application needs to handle write errors it is not safe as buffered data flushed on close may be lost and the error swallowed.


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

Now, you example:

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

Can be written as:

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

It's important to note that in order to use the try-with-resource approach, your resource need to implement a new interface called java.lang.AutoCloseable that was introduced in Java 7.

Also, you can include a number of resources in a try-with-resource block, just separate them with ;

   try (       BufferedWriter bw1 = new BufferedWriter(new FileWriter("test1.txt"));       BufferedWriter bw2 = new BufferedWriter(new FileWriter("test2.txt"))   ) {       // Do something useful with those 2 buffers!   }   // bw1 and bw2 will be closed in any case