本文介绍了使用Apache commons-io IOUtils.closeQuietly安全吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是代码

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

安全与否?据我了解,当我们关闭BufferedWriter时,它将刷新其缓冲区到基础流,并且可能由于错误而失败.但是IOUtils.closeQuietly API指出,任何异常都将被忽略.

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.

是否可能由于IOUtils.closeQuietlyly导致数据丢失不被注意?

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

推荐答案

关于closeQuietly()的javadoc,代码应如下所示:

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()不能用于一般用途,而不能直接在Closable上调用close().它的预期用例是确保finally块内的闭合-在此之前,必须完成所有需要的错误处理.

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.

这意味着,如果要在调用close()flush()的过程中对异常做出反应,则必须以常规方式对其进行处理.在您的finally块中添加closeQuietly()仅可确保关闭,例如当刷新失败并且没有在try块中调用close时.

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.

这篇关于使用Apache commons-io IOUtils.closeQuietly安全吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-17 17:21