java在windows中删除目录

标签 java windows

我尝试使用 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/

相关文章:

java - 如果在 for 语句中使用了 StatementExpressionList,ForInit 的值何时会被丢弃?

java - 如何运行 Maven 站点以及正常的安装/打包目标

java - 多个 Spring Batch 作业并发执行导致 Spring Batch 元数据表中出现死锁

c++ - C++打开文件夹的方法

windows - 适用于 Windows 的 Jetty 服务器

c++ - PARITY_NONE C++ Windows 中的关键字?

Java:我们可以将集合转换为数组列表吗?

java - 为什么我已经注册了警报却收不到接近警报?

java - 生成的 jar 文件问题切换 Windows/Linux 操作系统

windows - Procmon 的命令行版本