2015-06-22 79 views
0

想知道Java中是否有查找功能。 就像在Linux中,我们使用下面的命令来查找文件:如何在Java中使用find命令

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 /测试/ java包是常见的,它有很多里面的目录包含大量.java文件的。 我需要一种方法来获取所有这些.java文件的绝对路径。

+2

你可以看看[遛文件树](https:// docs.oracle.com/javase/tutorial/essential/io/walk.html)和[查找文件](https://docs.oracle.com/javase/tutorial/essential/io/find.html) – MadProgrammer

+0

您的标题会比如“在Java中如何模拟/实现*(等)找到命令”更好,因为如何“使用”它的答案是在子进程中调用它。 –

回答

1

您可以使用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> 

摇篮依赖性:

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

谢谢,这工作。可能就是我在找的东西。 – newtocoding

0

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

+0

这不是更好的评论吗? – 2015-06-22 07:46:35

+1

@Tichodroma,恕我直言,不,因为这回答了OP的问题。 – AlexR

+0

@Tichodroma - 我倾向于在这里同意Alex的观点。我认为问题是这个问题并不是那么好,它的答案是这样的。但亚历克斯是对的 - 它回答了这个问题 - 所以我真的不想违背他。 – jww

0

这里有一个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); 
    } 
    } 
}