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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/38609492/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-11-03 03:35:07  来源:igfitidea点击:

How to use Java 8 `Files.find` method?

javafile-iopathjava-8

提问by

I am trying to write an app to use Files.findmethod in it.

我正在尝试编写一个应用程序以Files.find在其中使用方法。

Below program works perfectly :

下面的程序完美运行:

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

This works fine and gives me a list of files ending with .txt( aka text files ) :

这工作正常,并为我提供了以.txt(又名文本文件)结尾的文件列表:

hello.txt
...

But below program does not show anything :

但下面的程序没有显示任何内容:

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

But it does not show anything :(

但它没有显示任何内容:(

Here is my home folder hiearchy (lsresult) :

这是我的主文件夹层次结构(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

So whats going wrong with path.getFileName().equals("workspace")?

那么有什么问题path.getFileName().equals("workspace")呢?

采纳答案by David

Path.getFilename() does not return a string, but a Path object, do a getFilename().toString().equals("workspace")

Path.getFilename() 不返回一个字符串,而是一个 Path 对象,做一个 getFilename().toString().equals("workspace")

回答by Yassin Hajaj

Use the following and look at the console. Maybe none of your files contains workspacein it

使用以下并查看控制台。也许你的文件都不包含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;
});