delete temporary file in java

sunil picture sunil · Jun 22, 2009 · Viewed 32.3k times · Source

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

Answer

Mnementh picture Mnementh · Jun 22, 2009

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.