delete temporary file in java

前端 未结 4 1445
伪装坚强ぢ
伪装坚强ぢ 2021-01-03 23:26

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.dele         


        
相关标签:
4条回答
  • 2021-01-03 23:33

    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.

    0 讨论(0)
  • 2021-01-03 23:42

    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.

    0 讨论(0)
  • 2021-01-03 23:47

    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!

    0 讨论(0)
  • 2021-01-03 23:47

    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();
       }
    
    }
    
    0 讨论(0)
提交回复
热议问题