File.delete () does not delete the new file if System.gc () is not called

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

Firstly, here is my configuration:

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

The code is as follows:

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

Output Error Trace:

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

This error is resolved if I uncomment System.gc (), which in my opinion is bad. It seems that Windows stores some resources in a file, even if it is never used.

My question is:

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

thanks in advance

+6
source share
1 answer

Object finalise() methods usually close the resources that were used by the object, for example. I / O stream objects. They usually call the close() method, which is usually called in the finally block.

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

+1
source

Source: https://habr.com/ru/post/984502/


All Articles