无法通过Java删除目录
在我的应用程序中,我编写了从驱动器中删除目录的代码,但是当我检查文件的删除功能时,它不会删除该文件。我写过这样的内容
//Code to delete the directory if it exists
File directory = new File("c:\\Report\\");
if(directory.exists())
directory.delete();
The directory is not in use: 仍然无法删除该目录。
In my application I have written the code to delete the directory from drive but when I inspect the delete function of File it doesn't delete the file. I have written some thing like this
//Code to delete the directory if it exists
File directory = new File("c:\\Report\\");
if(directory.exists())
directory.delete();
The directory is not in use: still it is not able to delete the directory.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
在Java中,目录删除只能针对空目录,这会导致类似以下的方法:
这个方法将删除您的文件夹,即使非空目录,也不会出现任何麻烦(除非该目录被操作系统锁定)。
in Java, directory deletion is possible only for empty directory, which leads to methods like the following :
This one will delete your folder, even if non-empty, without troubles (excepted when this directory is locked by OS).
为什么要发明一个带有递归删除方法的轮子?看看 apache commons io。
https://commons.apache.org/proper/commons-io/ javadocs/api-1.4/
或者
这就是您所需要的。
还有很多有用的方法来操作文件......
Why to invent a wheel with methods to delete recursively? Take a look at apache commons io.
https://commons.apache.org/proper/commons-io/javadocs/api-1.4/
OR
That is all you need.
There is also plenty of useful methods to manipulate files...
查看文档:
您是否确保该目录为空(也没有隐藏文件)?
Looking at the docs:
Did you make sure that the directory is empty (no hidden files either) ?
该目录必须为空才能删除它。如果不为空,则需要使用 File.listFiles() 和 File.delete() 递归删除它
The directory must be empty to delete it. If it's not empty, you need to delete it recursively with File.listFiles() and File.delete()
另外两种可能性(除了目录不为空之外):
Two other possibilities (besides the directory not being empty):