Recursively list all files & folders of input directory in java (example)

  1. Given an input directory or folder, we would like to list all files & folders in a directory.
  2. We will get current working directory and print all files & folder of input directory in java.
  3. We will use listFiles method of File class to get all files or folders (of current directory).
    • Then, we will print all contents of input directory.

Program – recursively list all files & directories (folders) in java (example)

package org.learn;

import java.io.File;

public class ListFilesRecursively {
    public static void main(String[] args) {
        String currentDirectory = System.getProperty("user.dir");
        System.out.println("Listing the files/folders of input directory - "+currentDirectory);
        //pass the input directory
        traverseFiles(new File(currentDirectory));
    }

    private static void traverseFiles(File inputFile) {
        File[] listFiles = inputFile.listFiles();
        for(File file: listFiles) {
            if(file.isDirectory()) {
                System.out.println("Directory:"+file.getAbsolutePath());
                traverseFiles(file);
            } else {
                System.out.println("File:"+file.getAbsolutePath());
            }
        }
    }
}

Output – print all files & directories (folders) recursively in java

Listing the files/folders of input directory - c:\data\db
Directory:c:\data\db
File:c:\data\db\collection-0-2086694220802165662.wt
File:c:\data\db\collection-103--5255221449412732250.wt
File:c:\data\db\collection-105--5255221449412732250.wt
File:c:\data\db\collection-108--5255221449412732250.wt
File:c:\data\db\collection-110--5255221449412732250.wt
File:c:\data\db\collection-113--5255221449412732250.wt
File:c:\data\db\collection-119--5255221449412732250.wt
File:c:\data\db\collection-121--5255221449412732250.wt
Directory:c:\data\db\diagnostic.data
File:c:\data\db\diagnostic.data\metrics.2016-09-30T12-42-56Z-00000
File:c:\data\db\diagnostic.data\metrics.2016-10-04T05-59-32Z-00000
File:c:\data\db\diagnostic.data\metrics.2016-10-06T12-23-26Z-00000
File:c:\data\db\index-99--5255221449412732250.wt
Directory:c:\data\db\journal
File:c:\data\db\journal\WiredTigerLog.0000000008
File:c:\data\db\journal\WiredTigerPreplog.0000000001
File:c:\data\db\journal\WiredTigerPreplog.0000000002
File:c:\data\db\mongod.lock
File:c:\data\db\sizeStorer.wt
File:c:\data\db\storage.bson
File:c:\data\db\WiredTiger
File:c:\data\db\WiredTiger.lock
File:c:\data\db\WiredTiger.turtle
File:c:\data\db\WiredTiger.wt
File:c:\data\db\WiredTigerLAS.wt
File:c:\data\db\_mdb_catalog.wt
Scroll to Top