Java - Search for files in a directory

前端 未结 9 670
予麋鹿
予麋鹿 2020-11-29 05:12

This is supposed to be simple, but I can\'t get it - \"Write a program that searches for a particular file name in a given directory.\" I\'ve found a few examples of a hardc

9条回答
  •  借酒劲吻你
    2020-11-29 05:25

    With **Java 8* there is an alternative that use streams and lambdas:

    public static void recursiveFind(Path path, Consumer c) {
      try (DirectoryStream newDirectoryStream = Files.newDirectoryStream(path)) {
        StreamSupport.stream(newDirectoryStream.spliterator(), false)
                     .peek(p -> {
                       c.accept(p);
                       if (p.toFile()
                            .isDirectory()) {
                         recursiveFind(p, c);
                       }
                     })
                     .collect(Collectors.toList());
      } catch (IOException e) {
        e.printStackTrace();
      }
    }
    

    So this will print all the files recursively:

    recursiveFind(Paths.get("."), System.out::println);
    

    And this will search for a file:

    recursiveFind(Paths.get("."), p -> { 
      if (p.toFile().getName().toString().equals("src")) {
        System.out.println(p);
      }
    });
    

提交回复
热议问题