gpt4 book ai didi

Java.nio : most concise recursive directory delete

转载 作者:IT老高 更新时间:2023-10-28 20:48:47 25 4
gpt4 key购买 nike

我目前正在尝试以递归方式删除一个目录...奇怪的是,我能找到的最短的代码片段是以下构造,采用 ad-hoc 内部类 并在 < em>访客模式...

Path rootPath = Paths.get("data/to-delete");

try {
Files.walkFileTree(rootPath, new SimpleFileVisitor<Path>() {
@Override
public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {
System.out.println("delete file: " + file.toString());
Files.delete(file);
return FileVisitResult.CONTINUE;
}

@Override
public FileVisitResult postVisitDirectory(Path dir, IOException exc) throws IOException {
Files.delete(dir);
System.out.println("delete dir: " + dir.toString());
return FileVisitResult.CONTINUE;
}
});
} catch(IOException e){
e.printStackTrace();
}

来源:here

考虑到新的 nio API 消除了如此多的困惑和样板,这感觉非常笨拙和冗长......

有没有更短的方法来实现强制的递归目录删除?

我正在寻找纯原生 Java 1.8 方法,所以请不要链接到外部库...

最佳答案

您可以将 NIO 2 和 Stream API 结合起来。

Path rootPath = Paths.get("/data/to-delete");
// before you copy and paste the snippet
// - read the post till the end
// - read the javadoc to understand what the code will do
//
// a) to follow softlinks (removes the linked file too) use
// Files.walk(rootPath, FileVisitOption.FOLLOW_LINKS)
//
// b) to not follow softlinks (removes only the softlink) use
// the snippet below
try (Stream<Path> walk = Files.walk(rootPath)) {
walk.sorted(Comparator.reverseOrder())
.map(Path::toFile)
.peek(System.out::println)
.forEach(File::delete);
}
  • Files.walk - 返回 rootPath 下的所有文件/目录,包括
  • .sorted - 以相反的顺序对列表进行排序,因此目录本身位于包含子目录和文件之后
  • .map - 将 Path 映射到 File
  • .peek - 仅用于显示处理了哪个条目
  • .forEach - 对每个 File 对象调用 .delete() 方法

编辑 正如 @Seby 首次提到的那样现在被 @John Dough 引用Files.walk() 应该在 try-with-resource 构造中使用。感谢两者。

来自 Files.walk javadoc

If timely disposal of file system resources is required, the try-with-resources construct should be used to ensure that the stream's close method is invoked after the stream operations are completed.

编辑

这里有一些数字。
目录 /data/to-delete 包含 jdk1.8.0_73 的解压 rt.jaractivemq 的最新版本.

files: 36,427
dirs : 4,143
size : 514 MB

以毫秒为单位的时间

                    int. SSD     ext. USB3
NIO + Stream API 1,126 11,943
FileVisitor 1,362 13,561

两个版本都在不打印文件名的情况下执行。最大的限制因素是驱动器。不是实现。

编辑

关于选项 FileVisitOption.FOLLOW_LINKS 的一些附加信息。

假设以下文件和目录结构

/data/dont-delete/bar
/data/to-delete/foo
/data/to-delete/dont-delete -> ../dont-delete

使用

Files.walk(rootPath, FileVisitOption.FOLLOW_LINKS)

将遵循符号链接(symbolic link),并且文件 /tmp/dont_delete/bar 也将被删除。

使用

Files.walk(rootPath)

不会跟随符号链接(symbolic link),文件 /tmp/dont_delete/bar 不会被删除。

注意:切勿在不了解其作用的情况下将代码用作复制和粘贴。

关于Java.nio : most concise recursive directory delete,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35988192/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com