tags:

views:

821

answers:

4

I'm writing string to temperoray file(temp.txt) and I want that file should open after clicking button of my awt window it should delete when I close that file (after opening that file), how can do this please help me.

This is code what i have used to create temporary file in java

File temp = File.createTempFile("temp",".txt");

FileWriter fileoutput = new FileWriter(temp);
Bufferedwriter buffout = new BufferedWriter(fileoutput);
+1  A: 

Some links that might help you:

Bombe
+5  A: 

Hello, A file created by:

File temp = File.createTempFile("temp",".txt");

Will not be deleted, see javadoc, you have to call

temp.deleteOnExit();

so the JVM will delete the file on exit...

pgras
how can i open file after clicking button and temp.deleteOnExit is it delete when i close the file or close the myrunning application?
I think he just wants to delete the file when he's done with it as opposed to deleting it on application exit.
Harry Lime
So you want to 1- write data to some file and close it. 2- latter on open this file and display the data in a window. 3- delete this file once someone has looked at the data in a window... Did I get it?
pgras
+2  A: 

How about something like:

if (!temp.delete())
{
    // wasn't deleted for some reason, delete on exit instead
    temp.deleteOnExit();
}
Harry Lime
A: 

To perform an operation when clicking a button, you will need code something like this:

    button.addActionListener(new java.awt.event.ActionListener() {
        public void actionPerformed(ActionEvent event) {
            fileOperation();
        }
    }
...
private void fileOperation() {
    ... do stuff with file ...
}

You can probably find many examples with google. Generally the anonymous inner class code should be short and just translate the event and context into operations meaningful to the outer class.

Currently you need to delete the file manually with File.delete after you have closed it. If you really wanted to you could extends, say, RandomAccessFile and override close to delete after the close. I believe delete-on-close was considered as a mode for opening file on JDK7 (no idea if it is in or not).

Just writing to a file, as in your code, would be pointless. You would presumably want to delete the file after closing a read stream no the write stream. It's not a bad idea to avoid temporary files if you possibly can.

Tom Hawtin - tackline
but how can i open file? clicking the button(operation is like foe example double clicking on the text file) how can i do this by program?
Ah, how to cause clicking on the button to perform an action?
Tom Hawtin - tackline