Video in progress
The end of a file written with BufferedWriter sometimes goes missing. Why?
The last chunk is still in the buffer and never reached the disk: the writer was not closed or flushed. If the program exits with System.exit or just drops the writer, the buffer contents are lost.
📖 Answer
The symptom is clear: 10,000 lines were written, the file has 9,873, and the last line is cut off halfway. This is almost always an unclosed writer.
BufferedWriter w = Files.newBufferedWriter(out);
for (Order o : orders) {
w.write(o.toCsv());
w.newLine();
}
// no close(): the last ~8 KB stayed in memory
Java does not flush a writer automatically at GC time. Even if the object is collected, the buffer contents are simply lost.
The fix is try-with-resources:
try (BufferedWriter w = Files.newBufferedWriter(out)) {
for (Order o : orders) {
w.write(o.toCsv());
w.newLine();
}
}
Similar cases:
- creating the writer in one method, keeping it as a field, and never closing it;
System.exit()orkill -9: even if a shutdown hook runs, open writers are not flushed unless you close them yourself;PrintWriterswallows the error atclose()time, so you don't find out that it wasn't written.
Sign up to mark studied questions and save your progress.