Question

We put frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); if we want our program to close properly.

What if I want my java program to write something to a file and then close itself.

Which would be the best way to implement it?

Was it helpful?

Solution

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.

OTHER TIPS

You may want to use Runtime.addShutdownHook. A Shutdown Hook allow you to execute a thread before the VM shuts down.

Here is a small usage example :

public class Foo {

    public static void main(String... args) {
        Runtime.getRuntime().addShutdownHook(
            new Thread() {
                public void run() {
                    System.out.println("Hello");
                }
            }
        );
    }

} 
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top