How to display all the directories in a directory using Java



Problem Description

How to display all the directories in a directory?

Solution

Following example shows how to display all the directories contained in a directory making a filter which list method of File class.

import java.io.*;

public class Main { 
   public static void main(String[] args) {
      File dir = new File("F:");
      File[] files = dir.listFiles();
      FileFilter fileFilter = new FileFilter() {
         public boolean accept(File file) {
            return file.isDirectory();
         }
      };
      files = dir.listFiles(fileFilter);
      System.out.println(files.length);
      
      if (files.length == 0) {
         System.out.println("Either dir does not exist or is not a directory");
      } else {
         for (int i = 0; i< files.length; i++) {
            File filename = files[i];
            System.out.println(filename.toString());
         }
      }
   }
}

Result

The above code sample will produce the following result.

14
F:\C Drive Data Old HDD
F:\Desktop1
F:\harsh
F:\hharsh final
F:\hhhh
F:\mov
F:\msdownld.tmp
F:\New Folder
F:\ravi
F:\ravi3
F:\RECYCLER
F:\System Volume Information
F:\temp
F:\work

The following is an another example of display all the directories in a directory in Java

import java.io.File;
import java.io.IOException;

public class FileDisplay { 
   public static void main(String[] args) {
      File currentDir = new File(".");
      displayDirectoryContents(currentDir);
   } 
   public static void displayDirectoryContents(File dir) {
      try { 
         File[] files = dir.listFiles();
         for (File file : files) {
            if (file.isDirectory()) {
               System.out.println("directory:" + file.getCanonicalPath());
               displayDirectoryContents(file);
            } else {
               System.out.println("     file:" + file.getCanonicalPath());
            } 
         } 
      } catch (IOException e) {
         e.printStackTrace();
      } 
   } 
}

The above code sample will produce the following result.

file:/web/com/1481172458_94270/FileDisplay.java
file:/web/com/1481172458_94270/FileDisplay.class
java_directories.htm
Advertisements