Java Listing All Files In a Directory

One of the common file system needs during programming is to find all the files or subdirectories in a directory. In Java, it is pretty easy since java.io.File has simple methods to achieve this. The File class is capable of representing both files and directories. This enables us to handle them in identical fashion, but using a simple check, we can differentiate them in the code.

The following sample Java program lists all the files in a directory. For each entry found, we print its name indicating whether it is a directory or file. Note that the following example uses a Mac OS directory path (if you are using Windows, replace it with a path of the form – c:/dir1.

import java.io.File;

/**
 * Lists all files and directories under a directory. Subdirectory entries are not listed.
 */
public class FileLister {
    
    public static void main(String[] args) {
        FileLister fl = new FileLister();
        String pathToDirectory = "/Users/jj/temp"; // replace this
        fl.listFilesInDirectory(pathToDirectory);
    }

    /**
     * 
     * @param pathToDirectory list all files/directories under this directory
     */
    private void listFilesInDirectory(String pathToDirectory) {
        File dir = new File(pathToDirectory);
        File[] files = dir.listFiles();
        
        for (File file:files) {
            if(file.isFile()) {
                System.out.println("FILE: "+file.getName());
            }
            else if(file.isDirectory()) {
                System.out.println("DIR:  "+file.getName());
            }
        }
    }
}

 

The following Java program lists all the files in a directory and also recursively traverses through subdirectories listing every file and directory. For large directory structures, this can take a lot of time and memory. We have also added logic to print the entries indicating its position in the overall directory hierarchy,

import java.io.File;

/**
 * List all files and directories under a directory recursively.
 */
public class FileListerRecursive {
    public static void main(String[] args) {
        FileListerRecursive fl = new FileListerRecursive();
        String pathToDirectory = "/Users/jj/temp";
        fl.listFilesInDirectoryAndDescendents(pathToDirectory,"");
    }

    /**
     * @param pathToDirectory
     * @param prefix This is appended with a dash every time this method is recursively called
     */
    private void listFilesInDirectoryAndDescendents(String pathToDirectory,String prefix) {
        File dir = new File(pathToDirectory);
        File[] files = dir.listFiles();
        
        for (File file:files) {
            if(file.isFile()) {
                System.out.println(prefix+"FILE: "+file.getName());
            }
            else if(file.isDirectory()) {
                System.out.println(prefix+"DIR:  "+file.getName());
                listFilesInDirectoryAndDescendents(file.getAbsolutePath(),prefix+"-");
            }
        }
    }
}

Do you have a programming problem that you are unable to solve? Please send us your problem and we will publish the solution on this site within 48 hours! Please email us.


Leave a Reply