我在Java中遇到了使用FileOutputStream
和BufferedWriter
的問題。FileOutputStream在空間不足時關閉
如果我的磁盤空間已滿,我試着寫,會拋出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
}
}
}
嘗試與資源 – 2013-06-28 13:39:55
如果write()拋出一個異常,然後flush()不執行...所以我不認爲這是幫助... – jamp
如果我不做一個.flush( )在.close()之前,.close()拋出一個IOException,因爲它將在執行.flush()時失敗(如果以前沒有在該方法內調用該方法)。如果我在try塊中執行.flush(),它會拋出一個IOException(當磁盤空間不足時),我可以毫無例外地調用.close()(BufferedWriter已經處於「刷新模式」並且.close () 將工作)。我確信有更好的解決方案。謝謝 – Matt