我在 Java 中使用FileOutputStream
and时遇到了问题。BufferedWriter
如果我的磁盘空间已满并且我正在尝试写入,它会抛出IOException
(这是正确的),但是当调用 writer.close() 时,它将无法关闭资源,抛出另一个IOException
并保持资源打开!
这是我的解决方法writer.flush()
。它似乎有效,但有没有更好的方法来处理这个问题?
BufferedWriter writer = null;
try {
writer = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(file), encoding));
StringBuilder buff = new StringBuilder();
writeToStream(buff, separator, data);
writer.write(buff.toString());
writer.flush(); // flush before closing to make sure there is enough space on disk to complete the close()
logger.trace("writeFile: file written, file={}", file);
} catch (IOException e) {
logger.error("writeFile: cannot write to file: {}", file, e);
throw new ... //some exception wrapper here
} finally {
if (writer != null) {
try {
writer.close();
} catch (IOException e) {
// ignore
}
}
}