在我的应用程序中,我编写了从驱动器中删除目录的代码,但是当我检查File的删除功能时,它不会删除该文件。我已经写了一些这样的事无法通过Java删除目录
//Code to delete the directory if it exists
File directory = new File("c:\\Report\\");
if(directory.exists())
directory.delete();
的directoryis不使用的仍是不能够删除目录
在我的应用程序中,我编写了从驱动器中删除目录的代码,但是当我检查File的删除功能时,它不会删除该文件。我已经写了一些这样的事无法通过Java删除目录
//Code to delete the directory if it exists
File directory = new File("c:\\Report\\");
if(directory.exists())
directory.delete();
的directoryis不使用的仍是不能够删除目录
锁定,目录删除仅适用于空目录,whi CH导致像下面的方法:
/**
* 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());
}
这一个会删除你的文件夹,即使非空,没有烦恼(当该目录是由OS锁定除外)。
的目录必须是空的将其删除。如果不是空的,你需要与File.listFiles()和File.delete()
两个其他的可能性(除了目录不为空)递归删除:
望着文档:
如果此路径名表示一个目录,然后将目录必须是为了空被删除。
你确定目录是空的(没有隐藏的文件)吗?
为什么要用递归方法删除轮子?看看Apache Commons io。 https://commons.apache.org/proper/commons-io/javadocs/api-1.4/
FileUtils.deleteDirectory(dir);
OR
FileUtils.forceDelete(dir);
这就是你所需要的。 还有很多有用的方法来操纵文件...
爱,当有东西已经写好。完全同意。感谢您的提醒。 – Aaron 2012-02-10 17:41:39
FileUtils#deleteDirectory和FileUtils#forceDelete实现它也递归地执行... – 2012-06-11 09:07:45