Site icon

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

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

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
Exit mobile version