Java delete()don';如果未调用System.gc(),则不能删除新文件
我目前在删除程序中从未使用过的文件时遇到问题 首先,这是我的配置:Java delete()don';如果未调用System.gc(),则不能删除新文件,java,file,Java,File,我目前在删除程序中从未使用过的文件时遇到问题 首先,这是我的配置: java版本:1.8.0_20 操作系统:Windows 7 Pro SP1 代码如下: File out = new File(workingDirectory, filePrefix + "download"); // cleanup old failed runs //System.gc(); // Bad! but seems the only way to pass the test boolean is
- java版本:1.8.0_20
- 操作系统:Windows 7 Pro SP1
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());
输出错误跟踪为:
junit.framework.AssertionFailedError:
Couldn't clear output location (isDeleted=false exists=true canWrite=true)
at [...]
如果我取消对System.gc()的注释,这个错误就会得到解决,在我看来,这是不好的。Windows似乎在该文件上保留了一些资源,即使它从未被使用过
我的问题是:
如果不使用System.gc(),如何解决此问题
感谢advance对象finalize()
方法通常关闭对象使用过的资源,例如IO流对象。它们通常调用通常在finally
块中调用的close()
方法
根据,当对象不再被引用时,GC将调用此方法。因为您不应该依赖这种机制,所以应该在删除文件之前显式关闭正在使用的资源。您可以使用
try with resources
语句自动关闭资源。您是如何创建该文件的?可能有一个未关闭的文件写入程序?对不起,我的错。因为它不是我的代码,所以我没有看到另一个真正创建文件并用一些字节填充它的方法。当然,使用了未关闭的流^^。是的,System.gc解决了这个问题,因为输出流既没有使用也没有关闭。谢谢,祝你今天愉快;)