如何在 Java 中使用查找命令

How to use the find command in Java

想知道 Java 中是否有查找功能。 就像在 Linux 中一样,我们使用以下命令查找文件:

find / -iname <filename> or find . -iname <filename> 

有没有类似的方法可以在Java中查找文件?我有一个目录结构,需要在某些子目录以及子子目录中找到某些文件。

Eg: I have a package abc/test/java 
This contains futher directories say 
abc/test/java/1/3 , abc/test/java/imp/1, abc/test/java/tester/pro etc. 

所以基本上 abc/test/java 包很常见,里面有很多目录,其中包含很多 .java 文件。 我需要一种方法来获取所有这些 .java 文件的绝对路径。

您可能不必重新发明轮子,因为名为 Finder 的库已经实现了 Unix 查找命令的功能:https://commons.apache.org/sandbox/commons-finder/

如果您想自己动手,这里有一个 java 8 片段可以帮助您入门。不过,您可能想阅读 Files.list 的注意事项。

public class Find {

  public static void main(String[] args) throws IOException {
    Path path = Paths.get("/tmp");
    Stream<Path> matches = listFiles(path).filter(matchesGlob("**/that"));
    matches.forEach(System.out::println);
  }

  private static Predicate<Path> matchesGlob(String glob) {
    FileSystem fileSystem = FileSystems.getDefault();
    PathMatcher pathMatcher = fileSystem.getPathMatcher("glob:" + glob);
    return pathMatcher::matches;
  }

  public static Stream<Path> listFiles(Path path){
    try {
        return Files.isDirectory(path) ? Files.list(path).flatMap(Find::listFiles) : Stream.of(path);
    } catch (IOException e) {
        throw new RuntimeException(e);
    }
  }
}

你可以使用 unix4j

Unix4jCommandBuilder unix4j = Unix4j.builder();
List<String> testClasses = unix4j.find("./src/test/java/", "*.java").toStringList();
for(String path: testClasses){
    System.out.println(path);
}

pom.xml 依赖关系:

<dependency>
    <groupId>org.unix4j</groupId>
    <artifactId>unix4j-command</artifactId>
    <version>0.3</version>
</dependency>

Gradle 依赖关系:

compile 'org.unix4j:unix4j-command:0.2'