Languages
[Edit]
EN

Java - get directories from a specific directory (recursive)

0 points
Created by:
isherwood
239

In this article, we would like to show you how to get all directories from a specific directory (including subdirectories) in Java.

Practical example

Project structure:

project/
  β”œβ”€β”€ one.txt
  └── directory1/
         β”œβ”€β”€ directory3/
         └── two.json
  └── directory2/
  └── three.html

1. Using File.listFiles method.

import java.io.File;

public class Example {

    public static void listDirectoriesInDirectory(File directoryPath) {
        File[] filesList = directoryPath.listFiles();
        for (File file : filesList) {
            if (file.isDirectory()) {
                System.out.println(file);
                listDirectoriesInDirectory(file);
            }
        }
    }

    public static void main(String[] args) {
        File directoryPath = new File("C:\\project");
        listDirectoriesInDirectory(directoryPath);
    }
}

Output:Β 

C:\project\directory1
C:\project\directory1\directory3
C:\project\directory2

2. Using Files.find method.

import java.nio.file.Files;
import java.nio.file.Paths;
import java.io.IOException;

public class Example {

    public static void main(String[] args) throws IOException {
        Files.find(Paths.get("C:\\project"),
                Integer.MAX_VALUE,   // the maximum number of directory levels to search
                (filePath, FileAttributes) -> FileAttributes.isDirectory())
                .forEach(System.out::println);
    }
}

Output:

C:\project
C:\project\directory1
C:\project\directory1\directory3
C:\project\directory2

3. Using Files.walkΒ method.

import java.nio.file.Files;
import java.nio.file.Paths;
import java.io.IOException;

public class Example {

    public static void main(String[] args) throws IOException {
        Files.walk(Paths.get("C:\\project"))
                .filter(Files::isDirectory)
                .forEach(System.out::println);
    }
}

Output:Β 

C:\project
C:\project\directory1
C:\project\directory1\directory3
C:\project\directory2

See also:

  1. Files.walk()
  2. Files.find()

Java - file operations

Native Advertising
πŸš€
Get your tech brand or product in front of software developers.
For more information Contact us
Dirask - we help you to
solve coding problems.
Ask question.

β€οΈπŸ’» πŸ™‚

Join