Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

File.delete() don't delete new File if System.gc() is not called [duplicate]

Tags:

java

file

I currently encounter a problem deleting a file that I never use in my program.

First, here is my config :

  • java version : 1.8.0_20
  • os : Windows 7 Pro SP1

The code is as follow :

 File out = new File(workingDirectory, filePrefix + "download");

 // cleanup old failed runs
 //System.gc(); // Bad! but seems the only way to pass the test
 boolean isDeleted = out.delete();
 assertTrue("Couldn't clear output location ("
            + " isDeleted="+isDeleted
            + " exists="+out.exists()
            + " canWrite="+out.canWrite()
            + ")", !out.exists());

The output error trace is :

junit.framework.AssertionFailedError:
Couldn't clear output location (isDeleted=false exists=true canWrite=true)
at [...]

This error is solved if I uncomment System.gc() which, in my opinion, is bad. It seems like Windows is holding some resources on the file even if it is never used.

My question is :

How can I solve this problem without using System.gc() ?

Thanks by advance

like image 788
Torarn Avatar asked Mar 31 '15 14:03

Torarn


People also ask

How will you delete an existing file?

Right-click the file, then click Delete on the shortcut menu. Tip: You can also select more than one file to be deleted at the same time. Press and hold the CTRL key as you select multiple files to delete.

How do you delete a file if already exists in Java?

files. deleteifexists(Path p) method defined in Files package: This method deletes a file if it exists. It also deletes a directory mentioned in the path only if the directory is empty. Returns: It returns true if the file was deleted by this method; false if it could not be deleted because it did not exist.

How do you force delete a file in Java?

Delete a file with Java IO 2.1 For the legacy File IO java.io. * , we can use the File. delete() to delete a file, and it will return boolean, true if file deletion success, false otherwise.


1 Answers

Object finalise() methods usually close resources that have been used by the object, e.g. IO stream objects. They typically invoke a close() method that would be usually called in a finally block.

According to the Javadocs, this method is called by the GC when the object is no longer referenced. Since you shouldn't count on this mechanism, you should explicitly close the resource being used before deleting the file. You can use a try-with-resources statement to automatically close the resource.

like image 151
M A Avatar answered Oct 01 '22 08:10

M A