Executing code when process finishes

Hi all,

I have an application which starts by reading data from a file.  When it ends, I want it to write data to the file, ready for next time.

What is the best way to do this?  More specifically:

1) How do I make the application execute code on quitting

and

2) Whats the best way to write over data in a file?  Delete the file then create a new one?
agreesAsked:
Who is Participating?

[Webinar] Streamline your web hosting managementRegister Today

x
 
sciuriwareConnect With a Mentor Commented:
Yet another solution: add a shutdown thread to your program,
just in case you exit from an unexpected spot:

     Runtime.getRuntime().addShutdownHook(new Rip());

    ......


    public class Rip extends Thread
    {
   // what must be done when I die ....
    }

;JOOP!
0
 
CEHJCommented:
1. You can make the application run the ccode at the end of main
2. Nothing special required - the file will be overwritten anyway
0
 
agreesAuthor Commented:
> 1. You can make the application run the ccode at the end of main

It's has a GUI so the application ends when the user closes one of the windows in a sequence of windows I create.  

My current best is idea to add a windowclosed listener to all the windows, but is there a better way?

2. Nothing special required - the file will be overwritten anyway

ok, so just something like this?:

    try {
        BufferedWriter out = new BufferedWriter(new FileWriter("outfilename"));
        out.write(myData);
        out.close();
    } catch (IOException e) {
    }

0
Never miss a deadline with monday.com

The revolutionary project management tool is here!   Plan visually with a single glance and make sure your projects get done.

 
CEHJConnect With a Mentor Commented:
>>My current best is idea to add a windowclosed listener to all the windows, but is there a better way?

Good idea

2. Yes, that'll do fine
0
 
objectsCommented:
Create an exit method that saves your file and exits the application.
Then whenever an event occurs that should close the application (eg. exit selected in menu) then call that exit() method.
0
 
ranaanjuCommented:
1. write your code at the end of the main function  in the finally block.
2. open file in the write mode, it will automatically delete if it exist and create it as new file.
0
 
CEHJCommented:
8-)
0
 
sciuriwareCommented:
What kind of expression is that CEHJ?  :<)
;JOOP!
0
All Courses

From novice to tech pro — start learning today.