1

So I have a printwriter that will occasionally write to a file ("occasionally" here meaning "periodically after a certain number of specified events").

Now if these events happen to be too few, the log file may end up empty when the application is terminated (Ctrl + C).

I could, of course, flush after every println, but that would defeat the purpose of having a non-auto-flush printwriter (which is the only kind that can be created anyway if I want to pass a File as a constructor argument).

Is there a onApplicationKill-thing in Java I could instrument to flush the writer once when the application is terminated? Or something to detect when the current thread is killed?

Gray
  • 115,027
  • 24
  • 293
  • 354
User1291
  • 7,664
  • 8
  • 51
  • 108

1 Answers1

3

You can use a shutdown hook:

Runtime.getRuntime().addShutdownHook(new Thread() {
  public void run() {
      ...
      writer.flush();
  }
});

It should also work if you kill it with Ctrl+C

Stefan
  • 444
  • 5
  • 16