newtocoding
newtocoding

Reputation: 77

How to use the find command in Java

Wanted to know if there is a find functionality in Java. Like in Linux we use the below command to find a file :

find / -iname <filename> or find . -iname <filename> 

Is there a similar way to find a file in Java? I have a directory structure and need to find certain files in some sub directories as well as sub-sub directories.

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. 

So basically the abc/test/java package is common and it has a lot of directories inside it which contain a lot .java files. I need a way to obtain the absolute path of all these .java files.

Upvotes: 1

Views: 3917

Answers (3)

quintin
quintin

Reputation: 837

You can use 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:

<dependency>
    <groupId>org.unix4j</groupId>
    <artifactId>unix4j-command</artifactId>
    <version>0.3</version>
</dependency>

Gradle dependency:

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

Upvotes: 3

roby
roby

Reputation: 3273

Here's a java 8 snippet to get you started if you want to roll your own. You might want to read up on the caveats of Files.list though.

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);
    }
  }
}

Upvotes: 0

AlexR
AlexR

Reputation: 115378

You probably do not have to re-invent the wheel because library named Finder already implements the functionality of Unix find command: https://commons.apache.org/sandbox/commons-finder/

Upvotes: 0

Related Questions