Petro Petro - 1 year ago 52
Java Question

.Close() is cutting off writer for a log file

I was looking into a problem with

causing cut-off issues. The program is running on two different servers, but had the same cutoff issue. It appears that the log file is not flushing properly. So I decided to dig into the
source code. I don't see a
being called. Am I missing something? Should we always call
? According to this answer, it shouldn't matter: Using flush() before close()

What I'm calling:

private static void write_to_file(String incoming){

Later on I call

The source code:

* Closes the stream and releases any system resources associated
* with it. Closing a previously closed stream has no effect.
* @see #checkError()
public void close() {
try {
synchronized (lock) {
if (out == null)
out = null;
catch (IOException x) {
trouble = true;

Log file:


Answer Source

As stated in the question you've correctly pointed out, calling close() on a stream is enough to flush whatever you've written to the stream. If the output is truncated, there are a few common pitfalls:

  • Your close() method is not called, e.g. if you put it in a catch block instead of finally ;)

  • Calling close() on a custom stream doesn't propagate the call to the underlying stream.

  • The problem can also be in encoding if you don't properly convert your String to bytes.