tags:

views:

160

answers:

3

Hai I have developed a standalone application in which when an user logs in, an log file will be created and when the application is closed the log file gets deleted.But when i shutdown the system with out closing the application the log file is not geting deleted.what can i do to delete my log file during shutdown or system crash that is when power supply is switched off when my application is running.Can someone help me to delete the log file during shutdown

Thanking you Chaithu

+11  A: 

If the VM is not properly shutdown it may not start the registered shutdown hooks. So in addition to File.deleteOnExit() (which I assume you are using, you’re not giving enough details) you should maybe also think about simply deleting all files you created in earlier invocations of your application when your application starts up.

Bombe
+3  A: 

you should be able to add a shutdown hook:

this example should help you. In short, this is the basic piece of code:

class MyShutdown extends Thread {
    public MyShutdown(SimpleHook managedClass) {
        super();
        this.managedClass = managedClass;
    }
    private SimpleHook managedClass;
    public void run() {
        System.out.println("MyShutDown thread started");
        try {
            managedClass.freeResources();
        } catch (Exception ee) {
            ee.printStackTrace();
        }
    }
}


public SimpleHook() {
    // set up service termination hook (gets called
    // when the JVM terminates from a signal):
    MyShutdown sh = new MyShutdown(this);
    Runtime.getRuntime().addShutdownHook(sh);
}

regards

Atmocreations
Shutdown hooks may not be executed when the application is not stopped cleanly (for example, in case of a system crash or stopping the process by force).
Jesper
+8  A: 

You can schedule a file for deletion when the JVM exits with the deleteOnExit() of the File class. However in a hard shutdown like a system crash, there is nothing you can do to ensure the log file is deleted cleanly. Your best option in this case would be to cleanup the next time the application starts if it's really that much of a problem.

Jon