web-dev-qa-db-ja.com

Java 8 `Files.find`メソッドの使い方は?

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

しかし、それは何も表示しません:(

これが私のホームフォルダの階層です(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")で何が問題になっているのでしょうか?

8
user6538026

Path.getFilename()は文字列を返しませんが、PathオブジェクトはgetFilename()。toString()。equals( "workspace")を実行します

5
David

以下を使用して、コンソールを確認してください。たぶんあなたのファイルのどれもそれに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;
});
1
Yassin Hajaj