tags:

views:

1142

answers:

3

I'm creating temporary file in java but i'm unable to delete it. This is the code I have written:

temp = File.createTempFile("temp", ".txt");
temp.deleteOnExit();
fileoutput = new FileWriter(temp);
buffout = new BufferedWriter(fileoutput);
+3  A: 

Add the following code (after you have done your operations with the file):

buffout.close();
fileoutput.close();
temp.delete();

As long as some stream on the file is open, it is locked (at least on the windows-implementation of the JVM). So it cannot be deleted.

It is good practice always to check if all opened streams get closed again after usage, because this is a bad memory-leak-situation. Your application can even eat up all available file-handles, that can lead to an unusable system.

Mnementh
He's already put deleteOnExit in there
oxbow_lakes
Was about to write the same thing. As a rule, deleteOnExit() is rather unreliable. I would do the above, but also check the return value from temp.delete() to make sure that all locks are removed.
mikek
As Mike said, I would not rely on deleteOnExit(). Additionally the temporary file is kept until the end of the program-execution, even if no longer needed. On a server-application that can be a long time. So explicitly deleting the file is preferable.
Mnementh
I have tried temp.delete() but it's returning false
@sunil: Are all open streams on this file closed first?
Mnementh
ya all streams are closed
Can you delete the file from Windows Explorer (assuming you're using Windows)?
oxbow_lakes
+3  A: 

There's a bug saying that if the file is open by filewriter or anything, it won't be deleted. On windows. Check if you close your file writers.

Another workaround would be installing a ShutdownHook which would manually delete the file.

Yoni Roit
deleteOnExit adds a shutdown hook
oxbow_lakes
A: 

You have to shut down a VM cleanly in order for the deleteOnExit to work properly (I suspect). On UNIX a kill would be a clean shutdown (i.e. the ShutdownHooks would be processed) whereas a kill -9 would be more like a force quit.

deleteOnExit definitely works for me!

oxbow_lakes
deleteOnExit keeps the file until the program ends. If the program only executes one action and stops afterwards that may be OK, but on a server-application the tempfiles are kept this way for a long time, accumulate and possibly eating up your inodes and your disk-space.
Mnementh
In the question, the use of deleteOnExit is not inappropriate - we've no idea what the specific usage pattern is. I would say that deleteOnExit is generally undesirable for a number of reasons (one being that it isn't reversible)
oxbow_lakes