I need to execute a method, (a method which creates a file), when I exit my program, how would I do this?
Since you are using Swing. When you close your application (by pressing the close button), you could simply hide your frame. Run the method you would want which creates the file and then exit the Frame. This would result in a graceful exit. Should there be any errors/exceptions, you can log that into a separate file.
Here is the code
package test;
import java.awt.event.ComponentAdapter;
import java.awt.event.ComponentEvent;
import javax.swing.JFrame;
public class TestFrame extends JFrame{
public TestFrame thisFrame;
public TestFrame(){
this.setSize(400, 400);
this.setVisible(true);
this.setDefaultCloseOperation(JFrame.HIDE_ON_CLOSE);
}
public static void main(String[] args){
TestFrame test = new TestFrame();
test.addComponentListener(new ComponentAdapter() {
@Override
public void componentHidden(ComponentEvent e) {
System.out.println("Replace sysout with your method call");
((JFrame)(e.getComponent())).dispose();
}
});
}
}
Please be aware of using shutdown hooks. As given in the Javadoc, it states that
When the virtual machine is terminated due to user logoff or system shutdown the underlying operating system may only allow a fixed amount of time in which to shut down and exit. It is therefore inadvisable to attempt any user interaction or to perform a long-running computation in a shutdown hook