FileOutputStream在空间不足时关闭

时间:2013-06-28 13:34:30

标签: java ioexception fileoutputstream diskspace bufferedwriter

我在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
               }
          }
     }

1 个答案:

答案 0 :(得分:2)

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

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