Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Recursively search for a directory in Java

What is the best way to find a directory with a specific name in Java? The directory that I am looking for can be located either in the current directory or one of its subdirectories.

like image 841
Liz Avatar asked May 28 '12 07:05

Liz


3 Answers

In Java 8 via the streams API:

Optional<Path> hit = Files.walk(myPath)
   .filter(file -> file.getFileName().equals(myName))
   .findAny();

The #walk is lazy, so any short-circuiting terminal operation will optimize the IO required.

like image 88
Kong Avatar answered Nov 06 '22 00:11

Kong


To walk the file tree, FileVisitor interface can be used. Please see the tutorial. Please see Find sample codes also.

like image 4
Wonil Avatar answered Nov 05 '22 22:11

Wonil


Your solution will include the use of File.listFiles(String)

java.io.File API reference

like image 3
Tom Avatar answered Nov 06 '22 00:11

Tom