2015-06-22 75 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); 
    } 
    } 
}