我尝试使用 java 删除一个目录,这是我的代码
public static void delDirectory(String path) throws IOException {
Path p = Paths.get(path);
delHelp(p);
}
private static void delHelp(Path p) throws IOException {
if (!p.toFile().exists()) {
return;
} else if(p.toFile().isFile()){
log.debug("delete file:" + p.toAbsolutePath().toString());
Files.delete(p);
}else if(p.toFile().isDirectory()){
for(Path subPath:Files.newDirectoryStream(p)){
delHelp(subPath);
}
log.debug("delete directory:"+p.toAbsolutePath().toString());
Files.delete(p);
}
}
在类 unix 系统上,它可以运行。在 Windows 上,代码 Files.delete(p)
实际上将目录移动到垃圾桶,因此当删除父目录时,代码将抛出异常: Exception in thread "main"java. nio.file.DirectoryNotEmptyException
对这种依赖于操作系统的行为有什么想法吗?我该如何解决这个问题?
最佳答案
实际的问题是您没有关闭 DirectoryStream
,这会在您尝试删除目录时导致 DirectoryNotEmptyException
。
来自Javadoc :
When not using the try-with-resources construct, then directory stream's close method should be invoked after iteration is completed so as to free any resources held for the open directory.
因此,您可以在完成后调用 close()
,或者在 try-with-resources 中使用它:
private static void delHelp(Path p) throws IOException {
if (!p.toFile().exists()) {
return;
} else if(p.toFile().isFile()){
Files.delete(p);
} else if(p.toFile().isDirectory()){
try (DirectoryStream<Path> ds = Files.newDirectoryStream(p)) {
for (Path subPath : ds){
delHelp(subPath);
}
}
Files.delete(p);
}
}
关于java在windows中删除目录,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33010030/