How to get the directories (only) from a folder using Java?


The ListFiles() method returns an array holding the objects (abstract paths) of all the files (and directories) in the path represented by the current (File) object.

The File Filter interface is filter for the path names you can pass this as a parameter to the listFiles() method. This method filters the file names passed on the passed filter.

To get the directories in a folder implement a FileFilter which accepts only directories and pass it as a parameter to the listFiles() method.

Following is a screen shot of the contents of the ExampleDirectory

Example

import java.io.File;
import java.io.FileFilter;
import java.io.IOException;
public class MyExample{
   public static void main(String args[]) throws IOException {
    //Creating a File object for directory
    File directoryPath = new File("D:\ExampleDirectory");
    //Creating filter for directories files
    FileFilter fileFilter = new FileFilter(){
         public boolean accept(File dir) {          
            if (dir.isDirectory()) {
               return true;
            } else {
               return false;
            }
         }
      };        
      File[] list = directoryPath.listFiles(fileFilter);
      System.out.println("List of the jpeg files in the specified directory:");  
      for(File fileName : list) {
         System.out.println(fileName);
      }  
   }
}

output

List of the jpeg files in the specified directory:
D:\ExampleDirectory\sample directory1
D:\ExampleDirectory\sample directory2
D:\ExampleDirectory\sample directory3
D:\ExampleDirectory\sample directory4

Example

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.stream.Stream;
public class ListOfFiles {
   public static void main(String[] args) throws IOException {
      Stream<Path> path = Files.walk(Paths.get("D:\ExampleDirectory"));
      path = path.filter(Files::isDirectory);
      path.forEach(System.out::println);
    }
}

Output

D:\ExampleDirectory
D:\ExampleDirectory\sample directory1
D:\ExampleDirectory\sample directory2
D:\ExampleDirectory\sample directory3
D:\ExampleDirectory\sample directory4

Updated on: 08-Feb-2021

716 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements