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

时间:2016-07-27 09:49:28

标签: 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);
    }
}

这很好用,并给我一个以.txt结尾的文件列表(又名文本文件):

hello.txt
...

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

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);
    }
}

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

这是我的主文件夹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

path.getFileName().equals("workspace")出现了什么问题?

2 个答案:

答案 0 :(得分:5)

Path.getFilename()不返回字符串,而是返回Path对象,执行getFilename()。toString()。equals(&#34; workspace&#34;)

答案 1 :(得分:1)

使用以下内容并查看控制台。也许你的文件中没有包含workspace

Files.find(p,maxDepth,(path, basicFileAttributes) -> {
    if (String.valueOf(path).equals("workspace")) {
        System.out.println("FOUND : " + path);
        return true;
    }
    System.out.println("\tNOT VALID : " + path);
    return false;
});