【问题标题】:FileOutputStream close when out of spaceFileOutputStream 空间不足时关闭
【发布时间】:2013-06-26 07:12:23
【问题描述】:

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

如果我的磁盘空间已满,我正在尝试写入,它会抛出IOException(这是正确的),但是当调用writer.close()时,它会关闭资源失败,抛出另一个@ 987654324@ 并保持资源打开!

这是我使用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
               }
          }
     }

【问题讨论】:

  • 如果 write() 抛出异常,则不执行 flush()...所以我认为它没有帮助...
  • 如果我在 .close() 之前不执行 .flush(),则 .close() 会抛出 IOException,因为它会在执行 .flush() 时失败(在内部调用如果之前没有做过该方法)。如果我在 try 块中执行 .flush() ,它将抛出 IOException (当磁盘空间不足时)并且我可以毫无例外地调用 .close() (BufferedWriter 将已经处于“刷新模式”并且 .close () 将工作)。我确信那里有更好的解决方案。谢谢

标签: java ioexception fileoutputstream diskspace bufferedwriter


【解决方案1】:

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

如果您有 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,则很容易重新创建。

【讨论】:

  • 我不明白在 BufferedWriter 上创建 Closer 的意义...您不需要自己显式关闭 OutputStream。 BufferedWriter 关闭底层编写器。我单独使用 FileOutputWriter(不使用 BufferedWriter)也遇到了同样的问题,所以即使使用 Closer,问题也会持续存在。谢谢
猜你喜欢
  • 1970-01-01
  • 2014-10-08
  • 2014-08-02
  • 2022-01-16
  • 2018-04-23
  • 1970-01-01
  • 2016-07-04
  • 1970-01-01
  • 2012-06-19
相关资源
最近更新 更多