You can try java.awt.event.WindowAdapter
and override this method:
windowClosing(WindowEvent e)
@AndrewThompson has made a good comment. Furthermore, here I have just assumed a very simple GUI-only scenario. Normally a thread which writes to a file should also care about closing the file channel, best in a finally-clause of a try/catch-block. The whole idea of closing resources in the very last moment is not so good in my opinion.
@Lind In the javadoc of Runtime.addShutdownHook
you can read:
"Shutdown hooks run at a delicate time in the life cycle of a virtual machine and should therefore be coded defensively. They should, in particular, be written to be thread-safe and to avoid deadlocks insofar as possible. They should also not rely blindly upon services that may have registered their own shutdown hooks and therefore may themselves in the process of shutting down. Attempts to use other thread-based services such as the AWT event-dispatch thread, for example, may lead to deadlocks."
So some care is necessary. If you use parts of your own program or your own file services in shutdownhook, it might not work, but would work in WindowAdapter. If you only rely directly on java.io-package in shutdownhook then this approach will probably work.
In general I repeat and confirm that resources should better not be closed so late. You must have a very good reason to do otherwise.