Java文件删除和System.gc() [英] Java file delete and System.gc()
问题描述
在我的应用程序中,我正在写一个文件来存储一些执行信息,一旦执行完成,我想删除临时文件。问题是甚至在文件关闭或清理后,我无法删除文件。我试过
pre $ Thread.sleep(1000);
file.delete();
并且没有删除文件。然后我创建了一个while循环while循环
while(!file.delete())
Thread.sleep(1000);
并且一直循环。然后我添加了
System.gc();
file.delete();
它起作用了!!!
我已经证实,我已经优雅地关闭或刷新文件。我想知道为什么我的代码与 System.gc()
?
这似乎表明你没有调用 close()
。
原因:在java开始的时候,使用 Object.finalize()
方法来清理垃圾回收,而对于I / O,它做了一个 close()
。
直到文件被使用(不关闭),文件不能在Windows上被删除。 p>
In my app I'm writing a file to store some execution info and once the execution is done I want to delete the temp file. The issue is even after file close or flush by streams I cannot delete the file. I tried
Thread.sleep(1000);
file.delete();
and that didn't delete the file either. I then created a while loop
while(!file.delete())
Thread.sleep(1000);
and it was looping forever. I then added
System.gc();
file.delete();
and it worked!!!
I have verified that I have gracefully closed or flushed the file. I want to know why my code worked with System.gc()
?
That seems to indicate that you did not call close()
.
Reason: in the begin time of java, the Object.finalize()
method was used to clean up on garbage collection, and for I/O it did a close()
.
Until the file is in use (not closed), the file cannot be deleted on Windows.
这篇关于Java文件删除和System.gc()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!