1

I have a java program which writes 1 file into multiple files, not all connections are open at the same time.

I want to add an method to remove all of these created files when the program is killed (by using ctrl-c in the command line).

Adding a shutdown hook is always executed when the object is shut down, I only want to remove them if the program is killed. Is there an RuntimeException I can catch?

Jetse
  • 1,706
  • 2
  • 16
  • 22

1 Answers1

2

Take a look at Runtime.getRuntime().addShutdownHook(). Here's an example.

Tomas Andrle
  • 13,132
  • 15
  • 75
  • 92
  • Does it recover the file to earlier state. I think the question is to roll back the operations performed in the files. – SenthilPrabhu May 15 '13 at 12:13
  • I think I found it because that site! First I will add a shutdownhook, and after all files are closed, I can remove this shutdownhook. – Jetse May 15 '13 at 12:14
  • @SenthilPrabhu the question says "remove all of these created files" - nothing about rolling back the contents. The new files can be easily removed from the shutdown hook. – Tomas Andrle May 15 '13 at 12:27
  • @TomA: Ok Tom..! I am sorry if it is the answer. The program writes one file content to multiple. So I just had a curiosity whether it can be rolled back to previous state. – SenthilPrabhu May 15 '13 at 12:32
  • Easiest way to enable a rollback-like functionality would be to first write the files into /tmp and then move them into place. – Tomas Andrle May 15 '13 at 13:14
  • @TomA: I had the Same Idea of using temp files then change the files. There is no guarantee that the application may terminate at replacing with old files. I think i ve to move to database only.. :) – SenthilPrabhu May 20 '13 at 08:42