问题描述
这是代码吗
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.closeQuietly 导致数据丢失不被注意?
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-block 中调用 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 安全吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!