How do I iterate through the files in a directory and it's sub-directories in Java?

ID : 20425

viewed : 8

Tags : javajava

Top 5 Answer for How do I iterate through the files in a directory and it's sub-directories in Java?

vote vote

95

You can use File#isDirectory() to test if the given file (path) is a directory. If this is true, then you just call the same method again with its File#listFiles() outcome. This is called recursion.

Here's a basic kickoff example:

package com.stackoverflow.q3154488;  import java.io.File;  public class Demo {      public static void main(String... args) {         File dir = new File("/path/to/dir");         showFiles(dir.listFiles());     }      public static void showFiles(File[] files) {         for (File file : files) {             if (file.isDirectory()) {                 System.out.println("Directory: " + file.getAbsolutePath());                 showFiles(file.listFiles()); // Calls same method again.             } else {                 System.out.println("File: " + file.getAbsolutePath());             }         }     } } 

Note that this is sensitive to StackOverflowError when the tree is deeper than the JVM's stack can hold. If you're already on Java 8 or newer, then you'd better use Files#walk() instead which utilizes tail recursion:

package com.stackoverflow.q3154488;  import java.io.File; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths;  public class DemoWithJava8 {      public static void main(String... args) throws Exception {         Path dir = Paths.get("/path/to/dir");         Files.walk(dir).forEach(path -> showFile(path.toFile()));     }      public static void showFile(File file) {         if (file.isDirectory()) {             System.out.println("Directory: " + file.getAbsolutePath());         } else {             System.out.println("File: " + file.getAbsolutePath());         }     } } 
vote vote

88

If you are using Java 1.7, you can use java.nio.file.Files.walkFileTree(...).

For example:

public class WalkFileTreeExample {    public static void main(String[] args) {     Path p = Paths.get("/usr");     FileVisitor<Path> fv = new SimpleFileVisitor<Path>() {       @Override       public FileVisitResult visitFile(Path file, BasicFileAttributes attrs)           throws IOException {         System.out.println(file);         return FileVisitResult.CONTINUE;       }     };      try {       Files.walkFileTree(p, fv);     } catch (IOException e) {       e.printStackTrace();     }   }  } 

If you are using Java 8, you can use the stream interface with java.nio.file.Files.walk(...):

public class WalkFileTreeExample {    public static void main(String[] args) {     try (Stream<Path> paths = Files.walk(Paths.get("/usr"))) {       paths.forEach(System.out::println);     } catch (IOException e) {       e.printStackTrace();     }   }  } 
vote vote

76

Check out the FileUtils class in Apache Commons - specifically iterateFiles:

Allows iteration over the files in given directory (and optionally its subdirectories).

vote vote

64

Using org.apache.commons.io.FileUtils

File file = new File("F:/Lines");        Collection<File> files = FileUtils.listFiles(file, null, true);      for(File file2 : files){     System.out.println(file2.getName());             }  

Use false if you do not want files from sub directories.

vote vote

52

For Java 7+, there is also https://docs.oracle.com/javase/7/docs/api/java/nio/file/DirectoryStream.html

Example taken from the Javadoc:

List<Path> listSourceFiles(Path dir) throws IOException {    List<Path> result = new ArrayList<>();    try (DirectoryStream<Path> stream = Files.newDirectoryStream(dir, "*.{c,h,cpp,hpp,java}")) {        for (Path entry: stream) {            result.add(entry);        }    } catch (DirectoryIteratorException ex) {        // I/O error encounted during the iteration, the cause is an IOException        throw ex.getCause();    }    return result; } 

Top 3 video Explaining How do I iterate through the files in a directory and it's sub-directories in Java?

Related QUESTION?