如何使用Java 8`Files.find`方法?

8 java file-io path java-8

我正在尝试编写一个应用程序来使用Files.find它的方法.

以下程序完美运作:

package ehsan;

/* I have removed imports for code brevity */

public class Main {
    public static void main(String[] args) throws IOException {
        Path p = Paths.get("/home/ehsan");
        final int maxDepth = 10;
        Stream<Path> matches = Files.find(p,maxDepth,(path, basicFileAttributes) -> String.valueOf(path).endsWith(".txt"));
        matches.map(path -> path.getFileName()).forEach(System.out::println);
    }
}
Run Code Online (Sandbox Code Playgroud)

这工作正常,并给我一个以.txt(也称为文本文件)结尾的文件列表:

hello.txt
...
Run Code Online (Sandbox Code Playgroud)

但是以下程序没有显示任何内容:

package ehsan;

public class Main {
    public static void main(String[] args) throws IOException {
        Path p = Paths.get("/home/ehsan");
        final int maxDepth = 10;
        Stream<Path> matches = Files.find(p,maxDepth,(path, basicFileAttributes) -> path.getFileName().equals("workspace"));
        matches.map(path -> path.getFileName()).forEach(System.out::println);
    }
}
Run Code Online (Sandbox Code Playgroud)

但它没有显示任何东西:(

这是我的主文件夹hiearchy(ls结果):

blog          Projects
Desktop       Public
Documents     Templates
Downloads     The.Purge.Election.Year.2016.HC.1080p.HDrip.ShAaNiG.mkv
IdeaProjects          The.Purge.Election.Year.2016.HC.1080p.HDrip.ShAaNiG.mkv.aria2
Music         Videos
Pictures      workspace
Run Code Online (Sandbox Code Playgroud)

那么什么出错path.getFileName().equals("workspace")

小智 5

Path.getFilename()不返回字符串,而是Path对象,执行getFilename()。toString()。equals(“ workspace”)

  • 谢谢,getFileName()实际上没有返回文件名不是很有趣!? (3认同)