Files.walk() OS-独立问题

Files.walk() OS-independency issue

我有以下代码,在 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(".*/\..*"))

使这个 OS 独立的正确方法是什么?

您不应将 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("."))

@Tunaki 建议的另一种解决方案是尝试用 OS 特定的文件分隔符替换正斜杠(如果它是 Windows 上的反斜杠字符,则需要对其进行转义):

.filter(path -> 
        !path.toAbsolutePath().toString().matches(".*"
                                        + Pattern.quote(File.separator) + "\..*"))