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);
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);
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.
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.
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!