无法通过 Java 删除目录
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/3987921/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
not able to delete the directory through Java
提问by Vipul
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 directoryis not in used still it is not able to delete the directory
该目录未使用仍然无法删除该目录
回答by Riduidel
in Java, directory deletion is possible only for empty directory, which leads to methods like the following :
在Java中,目录删除只能对空目录进行,导致方法如下:
/**
* Force deletion of directory
* @param path
* @return
*/
static public boolean deleteDirectory(File path) {
if (path.exists()) {
File[] files = path.listFiles();
for (int i = 0; i < files.length; i++) {
if (files[i].isDirectory()) {
deleteDirectory(files[i]);
} else {
files[i].delete();
}
}
}
return (path.delete());
}
This one will delete your folder, even if non-empty, without troubles (excepted when this directory is locked by OS).
这将删除您的文件夹,即使是非空的,也不会出现问题(除非该目录被操作系统锁定)。
回答by Ilja S.
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/
为什么要发明一个带有递归删除方法的轮子?看看 apache commons io。 https://commons.apache.org/proper/commons-io/javadocs/api-1.4/
FileUtils.deleteDirectory(dir);
OR
或者
FileUtils.forceDelete(dir);
That is all you need. There is also plenty of useful methods to manipulate files...
这就是你所需要的。还有很多有用的方法来操作文件......
回答by user268396
Looking at the docs:
查看文档:
If this pathname denotes a directory, then the directory must be empty in order to be deleted.
如果此路径名表示一个目录,则该目录必须为空才能被删除。
Did you make sure that the directory is empty (no hidden files either) ?
您是否确保该目录为空(也没有隐藏文件)?
回答by iirekm
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()
该目录必须为空才能删除它。如果它不为空,则需要使用 File.listFiles() 和 File.delete() 递归删除它
回答by Michael Borgwardt
Two other possibilities (besides the directory not being empty):
另外两种可能性(除了目录不为空):
- The user which runs the java program does not have write/delete permission for the directory
- The directory is used/locked by a different process (you write that it's not, but how have you confirmed this?)
- 运行java程序的用户没有目录的写/删除权限
- 该目录由不同的进程使用/锁定(您写道它不是,但是您如何确认这一点?)