List all directories of input path – scope operator & file filter in java

  • Given an input directory in a file system.
  • We would like to list or print its directories recursively.
    • We will traverse all directories and sub directories to list directories (only).

List folders & directories using scope operator & fileFilter (IO):

  • We will discuss couple of methods to list directories (refer trailing code).
    1. We will scope resolution operator to filter directories
      •  Method name: listDirectoriesUsingScope.
    2. We will write explicit file filter to list directories only.

List directories at input path – scope operator & file filter (java/example)

package org.learn;

import java.io.File;
import java.io.FilenameFilter;

public class ListDirectoriesOnly {
    private static int serialNumber = 0;

    public static void main(String[] args) {
        String currentDirectory = System.getProperty("user.dir");
        System.out.println("Listing directories using scope operator:"+currentDirectory);
        listDirectoriesUsingScope(new File(currentDirectory));

        serialNumber = 0;
        System.out.println("\nListing directories using explicit file filter");
        listDirectoriesUsingExplicitFilter(new File(currentDirectory));
    }

    private static void listDirectoriesUsingScope(File inputFile) {
        File[] listDirectories = inputFile.listFiles(File::isDirectory);
        for (File directory : listDirectories) {
            System.out.printf("%d. %s\n", ++serialNumber, directory.getAbsolutePath());
            listDirectoriesUsingScope(directory);
        }
    }

    private static void listDirectoriesUsingExplicitFilter(File inputFile) {
        File[] listDirectories = inputFile.listFiles(new FilenameFilter() {
            @Override
            public boolean accept(File current, String name) {
                return new File(current, name).isDirectory();
            }
        });

        for (File directory : listDirectories) {
            System.out.printf("%d. %s\n", ++serialNumber, directory.getAbsolutePath());
            listDirectoriesUsingExplicitFilter(directory);
        }
    }
}

Print directories at given path path –  scope operator & file filter (java/example)

Listing directories using scope operator:C:\data
1. C:\data\db
2. C:\data\db\diagnostic.data
3. C:\data\db\journal

Listing directories using explicit file filter
1. C:\data\db
2. C:\data\db\diagnostic.data
3. C:\data\db\journal
Scroll to Top