如何在Java中使用find命令

如何在Java中使用find命令,java,linux,command,Java,Linux,Command,想知道Java中是否有查找功能。 与Linux一样,我们使用以下命令查找文件: find / -iname <filename> or find . -iname <filename> 所以基本上,abc/test/java包是通用的,它有很多目录,其中包含很多.java文件。 我需要一种方法来获取所有这些.java文件的绝对路径。您可能不必重新发明轮子,因为名为Finder的库已经实现了Unix find命令的功能:如果您想自己启动,这里有一个java 8代码片段。

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

find / -iname <filename> or find . -iname <filename> 
所以基本上,abc/test/java包是通用的,它有很多目录,其中包含很多.java文件。
我需要一种方法来获取所有这些.java文件的绝对路径。

您可能不必重新发明轮子,因为名为Finder的库已经实现了Unix find命令的功能:

如果您想自己启动,这里有一个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);
    }
  }
}
公共类查找{
公共静态void main(字符串[]args)引发IOException{
Path Path=Path.get(“/tmp”);
Stream matches=listFiles(path).filter(matchesGlob(“**/that”);
matches.forEach(System.out::println);
}
私有静态谓词matchesGlob(字符串glob){
FileSystem FileSystem=FileSystems.getDefault();
PathMatcher PathMatcher=fileSystem.getPathMatcher(“glob:+glob”);
返回路径匹配器::匹配;
}
公共静态流列表文件(路径){
试一试{
return Files.isDirectory(path)?Files.list(path).flatMap(Find::listFiles):Stream.of(path);
}捕获(IOE异常){
抛出新的运行时异常(e);
}
}
}

您可以使用unix4j

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

你可以看看,你的标题应该是“如何在Java中模拟/实现(etc)find命令”,因为如何“使用”它的答案是在子流程中调用它。这不是更好的注释吗?@Tichodroma,IMHO no,因为这回答了OP的问题。@Tichodroma-我倾向于同意Alex的观点。我认为问题在于这个问题不是很好,它引出了这样的答案。但是亚历克斯是对的,这回答了问题,所以我真的不想反对他。
Unix4jCommandBuilder unix4j = Unix4j.builder();
List<String> testClasses = unix4j.find("./src/test/java/", "*.java").toStringList();
for(String path: testClasses){
    System.out.println(path);
}
<dependency>
    <groupId>org.unix4j</groupId>
    <artifactId>unix4j-command</artifactId>
    <version>0.3</version>
</dependency>
compile 'org.unix4j:unix4j-command:0.2'