【问题标题】:How to use the find command in Java如何在 Java 中使用 find 命令
【发布时间】:2015-09-07 13:29:23
【问题描述】:

想知道 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 文件的绝对路径。

【问题讨论】:

  • 你的标题最好是“如何emulate/implement (etc) find command in Java”,因为如何“使用”它的答案是调用它在一个子进程中。

标签: java linux command


【解决方案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>

Gradle 依赖:

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

【讨论】:

    【解决方案2】:

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

    【讨论】:

    • 这不是评论更好吗?
    • @Tichodroma,恕我直言不,因为这回答了 OP 的问题。
    • @Tichodroma - 我倾向于同意 Alex 的观点。我认为问题在于这个问题并不是那么好,它的引出答案是这样的。但亚历克斯是对的——它回答了问题——所以我真的不想反对他。
    【解决方案3】:

    如果您想自己动手,这里有一个 java 8 sn-p 可以帮助您入门。不过,您可能需要阅读 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);
        }
      }
    }
    

    【讨论】:

      猜你喜欢
      • 2019-12-24
      • 2015-11-15
      • 1970-01-01
      • 1970-01-01
      • 2016-01-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多