gpt4 book ai didi

java - FileOutputStream 空间不足时关闭

转载 作者:行者123 更新时间:2023-12-02 06:55:53 25 4
gpt4 key购买 nike

我在 Java 中使用 FileOutputStreamBufferedWriter 时遇到了问题。

如果我的磁盘空间已满并且我正在尝试写入,它将抛出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
}
}
}

最佳答案

您应该尝试按照打开资源的相反顺序关闭所有资源。在这里,您尝试仅关闭一个。

如果您有 Java 7,请使用 try-with-resources 语句。如果不这样做,最好的方法是使用 Guava's Closer (自版本 14.0 起可用):

final Closer closer = Closer.create();
final FileOutputStream out;
final OutputStreamWriter writer;
final BufferedWriter buffered;

try {
out = closer.register(new FileOutputStream(file), encoding));
writer = closer.register(new OutputStreamWriter(out));
buffered = closer.register(new BufferedWriter(writer));
// do stuff
} catch (IOException e) {
throw closer.rethrow(e);
} finally {
closer.close();
}

如果您没有Closer,则很容易重新创建。

关于java - FileOutputStream 空间不足时关闭,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17365948/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com