6

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

Torarn
  • 352
  • 2
  • 10

1 Answers1

1

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.

M A
  • 69,673
  • 13
  • 131
  • 165
  • 1
    Sorry, my bad. As it is not my code, I didn't see another method that really created the file and fill it with some bytes. And of course an unclosed stream was used ^^. So yes, System.gc solved the problem only because the output stream were neither used nor closed. Thanks and have a good day ;) – Torarn Apr 01 '15 at 08:08