How to recursively list all files in a directory and sub-directory in Java

Hello, guys if you are looking for a Java program to recursively list all files in a directory or sub-directory in Java then you have come to the right place. Earlier, I have shared the best Java Programming courses and In this article, I will show you how you can use the SimpleFileVistor class from java.nio package to recursive list all files and directories inside a given directory. The API also provides you control over whether to list only files or directories when you are navigating recursively. This makes it very useful for archiving programs or creating build tools like Maven or any Java program which has to deal with files and directories. 



How to recursively list all files in a directory or its sub-directory in Java

Here is our complete Java program to list all files and directories from a given Path. In this program, I will show you two ways to recursively find all files and directories. In the first method, you will list both files and directories, while in the second example you will list files. 

If you want to learn more about Java File API, I highly recommend you to join a comprehensive Java course like The Complete Java Programming Masterclass by Tim Buchalaka and his team on Udemy. This 80+ hour course is one of the best and most up-to-date courses to learn Java for beginners. 

How to recursively list all files in a directory and sub-directory in Java


Now, let's jump into the code to see things in action:
import java.io.File;
import java.io.IOException;
import java.nio.file.FileVisitResult;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.SimpleFileVisitor;
import java.nio.file.attribute.BasicFileAttributes;

/**
* Java Program to recursively list all files inside a directory or its
* sub-directory in Java.
*
* @author Javin Paul
*/
public class Testing {

    public static void main(String args[]) {
        System.out.println("Recursively listing all files using 
                               JDK 7 walkFileTree() method");
        walkDirectory("target");

        System.out.println("Recursively list all files only in Java,
                              Alternative way");
        listFilesOnly(new File("target"));

    }

    public static void walkDirectory(String path) {
        Path dir = Paths.get(path);
        try {
            Files.walkFileTree(dir, new ListFileVisitor());
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public static void listFilesOnly(File root) {
        if (root.isDirectory()) {
            File[] allFilesAndDirectories = root.listFiles();
            for (File f : allFilesAndDirectories) {
                listFilesOnly(f);
            }
        } else {
            System.out.println(root.getAbsolutePath());
        }
    }
}

class ListFileVisitor extends SimpleFileVisitor {

    @Override
    public FileVisitResult visitFile(Path file, BasicFileAttributes attrs)
                     throws IOException {
        System.out.println(file);
        return FileVisitResult.CONTINUE;
    }
}


Output:
Recursively listing all files using JDK 7 walkFileTree() method
target\classes\Helloworld.class
target\classes\HelloworldTest.class
target\classes\Instrument.class
target\maven-archiver\pom.properties
target\maven-status\maven-compiler-plugin\compile\default-compile\createdFiles.lst
target\maven-status\maven-compiler-plugin\compile\default-compile\inputFiles.lst
target\Test-0.0.1-SNAPSHOT.jar

Recursively list all files only in Java, Alternative way
D:\Programs\Test\target\classes\Helloworld.class
D:\Programs\Test\target\classes\HelloworldTest.class
D:\Programs\Test\target\classes\Instrument.class
D:\Programs\Test\target\maven-archiver\pom.properties
D:\Programs\Test\target\maven-status\maven-compiler-plugin\compile
                 \default-compile\createdFiles.lst
D:\Programs\Test\target\maven-status\maven-compiler-plugin\compile
                 \default-compile\inputFiles.lst
D:\Programs\Test\target\Test-0.0.1-SNAPSHOT.jar

Files.walkFileTree() in Java

If you provide a starting point and a file visitor, it will invoke various methods on the file visitor as it walks through the file in the file tree. Java programmers should use this if they are developing a recursive copy, a recursive move, a recursive delete, or a recursive operation that sets permissions or performs another operation on each of the files.

If you like to use third-party open-source utility libraries like Apache Commons-IO then you can also use their FileUtils class which has iterateFiles() and listFiles() methods. Instead of using these methods, you can use them as well. 

And, if you just want to list all files recursively with no filtering,  you can also use the FileUtils.listFiles(dir, TrueFileFilter.INSTANCE, TrueFileFilter.INSTANCE), where dir is a File object that points to the base directory You might want to consider using listFilesAndDirs(), as listFiles() does not return empty folders

That's all about how to recursively list all files in a given directory and their sub-directories in Java. The java.nio package has some powerful tools and classes to interact with the local file system and they are also enhanced significantly on Java 7. You can use them to write powerful tools and utility in Java.


No comments :

Post a Comment