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
}
}
}
try-with-resources –
write()가 예외를 throw하면 flush()가 실행되지 않으므로 ... 도움이되지 않는다고 생각합니다. – jamp
.flush (.close() 전에 .close()는 .flush() (이전에 완료되지 않은 경우 메소드 내부에서 호출 됨)를 수행 할 때 실패하므로 IOException을 발생시킵니다. try 블록에서 .flush()를 수행하면 디스크 공간이 부족한 경우 IOException이 발생하고 예외없이 .close()를 호출 할 수 있습니다. BufferedWriter는 이미 "플러시 모드"로, .close()가 작동합니다). 거기에 더 좋은 해결책이 있다고 확신합니다. 감사합니다 – Matt