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

前端 未结 4 396
隐瞒了意图╮
隐瞒了意图╮ 2020-12-24 05:42

Is this code

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


        
4条回答
  •  爱一瞬间的悲伤
    2020-12-24 06:17

    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.

提交回复
热议问题