delete temporary file in java

2020-03-01 04:55发布

问题:

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

回答1:

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.



回答2:

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.



回答3:

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!



回答4:

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

}


回答5:

import java.io.File;
import java.io.IOException;

public class TemporaryFileExample
{
   public static void main(String[] args)
   {
      File temp;
      try
      {
         temp = File.createTempFile("myTempFile", ".txt");

         System.out.println("Temp file created : " + temp.getAbsolutePath());

         //temp.delete(); //For deleting immediately

         temp.deleteOnExit(); //Delete on runtime exit

         System.out.println("Temp file exists : " + temp.exists());
      } catch (IOException e)
      {
         e.printStackTrace();
      }
   }
}