java file.delete() returns false but file.exists() returns true
There are any number of reasons why a file cannot be deleted; it may not exist, it may be a non-empty directory, you may not have closed all resources using it, and your program may not have permission to do so, to name a few.
Unfortunately the File.delete() method provides very little information as to why; it's pretty much up to you to poke around and figure it out. But there's good news; you don't want to use File in the first place.
Java 7 introduced the new java.nio.file package which is a much more robust file access API. It provides the concept of an abstract Path and separates concrete operations into the Files class, in particular it provides Files.delete() which is documented to raise clear exceptions describing the reasons deletion might fail.
Use Path and Files; you'll be glad you did.

本文探讨了Java中使用File类删除文件时可能遇到的问题及原因,并介绍了Java 7引入的java.nio.file包如何提供更强大的文件访问API。通过对比File.delete()与Files.delete(),展示了后者如何通过清晰的异常来提高错误诊断能力。

1976

被折叠的 条评论
为什么被折叠?



