sunil
sunil

Reputation:

delete temporary file in java

I'm creating a 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);

Upvotes: 25

Views: 41883

Answers (4)

vineetawaw kkklll
vineetawaw kkklll

Reputation: 11

Code to close the inpustream and outputstream:

    FileInputStream in = new FileInputStream();

     ArrayList list_in = new ArrayList<FileInputStream>();

     list_in.add(in);

     FileOutputStream out = new FileOutputStream();

     ArrayList list_out = new ArrayList<OutputputStream>();

     list_in.add(out);

     public do_before_exit()
     {

      for(int i=0;i<list_in.size();i++)
      {
      FileInputStream in=(FileInputStream)list_in.get(i)
       FileInputStream out=(FileInputStream)list_out.get(i)

      in.close()
    out.close();
   }

}

Upvotes: 1

Mnementh
Mnementh

Reputation: 51331

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.

Upvotes: 28

oxbow_lakes
oxbow_lakes

Reputation: 134330

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!

Upvotes: 0

Yoni Roit
Yoni Roit

Reputation: 28696

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.

Upvotes: 3

Related Questions