gpt4 book ai didi

java - Files.walk() 操作系统独立性问题

转载 作者:行者123 更新时间:2023-11-29 07:35:46 25 4
gpt4 key购买 nike

我有以下在 Linux/Unix 下运行良好的代码:

Files.walk(Paths.get(getStartingPath()))
.filter(Files::isDirectory)
// Skip directories which start with a dot (like, for example: .index)
.filter(path -> !path.toAbsolutePath().toString().matches(".*/\\..*"))
// Note: Sorting can be expensive:
.sorted()
.forEach(operation::execute);

但是,在Windows下,这部分似乎不能正常工作:

     .filter(path -> !path.toAbsolutePath().toString().matches(".*/\\..*"))

使这个操作系统独立的正确方法是什么?

最佳答案

您不应将 Path 与硬编码文件分隔符相匹配。这势必会引起问题。

你在这里想要的是一种获取目录名称并在它以点开头的情况下跳过它的方法。您可以使用 getFileName() 检索目录名称:

Returns the name of the file or directory denoted by this path as a Path object. The file name is the farthest element from the root in the directory hierarchy.

然后你可以使用startsWith(".")查看它是否以点开头。

因此,你可以

.filter(path -> !path.getFileName().startsWith("."))

关于java - Files.walk() 操作系统独立性问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36117656/

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