0

我在 Java 中使用FileOutputStreamand时遇到了问题。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
               }
          }
     }
4

1 回答 1

2

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

如果您有 Java 7,请使用 try-with-resources 语句。如果你不这样做,最好的方法是使用GuavaCloser(从 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,则重新创建很容易。

于 2013-06-28T13:40:10.677 回答