【问题标题】:Delete directory recursively java not working [duplicate]递归删除目录java不起作用[重复]
【发布时间】:2017-01-09 00:23:15
【问题描述】:

如何删除包含 Java 内容的整个目录? 我已经尝试了一些代码,但它不起作用。

  public static void removeRecursive(Path path) throws IOException
{
    Files.walkFileTree(path, new SimpleFileVisitor<Path>()
    {
        @Override
        public FileVisitResult visitFile(Path file, BasicFileAttributes attrs)
                throws IOException
        {
            Files.delete(file);
            return FileVisitResult.CONTINUE;
        }

        @Override
        public FileVisitResult visitFileFailed(Path file, IOException exc) throws IOException
        {
            // try to delete the file anyway, even if its attributes
            // could not be read, since delete-only access is
            // theoretically possible
            Files.delete(file);
            return FileVisitResult.CONTINUE;
        }

        @Override
        public FileVisitResult postVisitDirectory(Path dir, IOException exc) throws IOException
        {
            if (exc == null)
            {
                Files.delete(dir);
                return FileVisitResult.CONTINUE;
            }
            else
            {
                // directory iteration failed; propagate exception
                throw exc;
            }
        }
    });
}

它抛出一个错误:

D:\MainDir\chantier : 讲课错误。 字符串索引超出范围:-1

这是我的道路 D:\MainDir\ch\Lot\dossier\mail.zip

我想用他的内容删除目录 ch\Lot\dossier\mail.zip 但我的功能只删除 \dossier\mail.zip 并抛出提到的错误

Ps : 我作为输入文件 D:\MainDir\ch

提前致谢

【问题讨论】:

  • 请添加完整的堆栈跟踪
  • 我认为FileVisitor 在这里不是一个好的选择。查看this question 获取一些简单的解决方案。
  • @jens 这是它显示的唯一错误
  • @ImaneJabal 一定还有更多。打印出堆栈跟踪

标签: java


【解决方案1】:

在目录中,您需要为每个文件执行此操作。您可以检查 .isDirectory() ,如果是这样,则从 .listFiles() 循环遍历其中的每个文件,直到完成传递给该方法的根目录中的所有内容。

Java 8 现在还提供 Files.walk 以更轻松地执行此操作,请查看文档 here

【讨论】:

    猜你喜欢
    • 2010-10-21
    • 2014-05-12
    • 2018-10-15
    • 1970-01-01
    • 2011-03-11
    相关资源
    最近更新 更多