Java Program to List Files And Directories

In the java.io.File class, methods list() and listFiles() are given with their overloaded forms to list the files and directory. We can use them in our program to get all files and directories in a particular directory or to get all files in directory and subdirectories. We can also get them through file extension. First, let us those methods.

Return TypeMethodDescription
String[]list()It returns all file and subdirectory names as String objects
using String array.
String[]list(FilenameFilter filter)It returns all file and subdirectory names whose name are
matched with given filter as String objects using String array.
File[]listFiles()It returns all file and subdirectory names as File objects
using File array.
File[]listFiles(FilenameFilter filter)It returns all file and subdirectory names whose name
are matched with a given filter as File objects using File array.
File[]listFiles(FileFilter filter)It returns all file and subdirectory names whose name are
matched with given FileFilter as File objects using File array.

In the above five methods:- The array will be empty if the directory is empty. They return null if abstract path name is not a directory, or if an I/O error occurs.

File[]listRoots()It returns An array of File objects denoting the available file system roots,
or null if the set of roots could not be determined.
The array will be empty if there are no file system roots.

Assume we have a “TestFile” directory in our current working directory, The hierarchy of “TestFile” directory is,

In TestFile,

  • abc.txt
  • Hello.java
  • index.html
  • dir1
    • abc11.txt
    • dir11
      • abc111.txt
      • abc112.java
    • dir12
  • dir2
    • dir21
      • abc211.txt
    • dir22
      • dir221
      • abc2211.pdf
    • dir23

Simple Java program to display all files and directory

import java.io.File;
public class DisplayFiles {

   public static void main(String[] args) {

      int count = 0;
      File dir = new File("TestFile");
      String[] file = dir.list();

      for(String str: file) {
         count++;
         System.out.print(str+" ");
      }

      System.out.println("\nTotal files = " 
                          + file.length );
   }
}

Output:-

dir2 Hello.java input.txt dir1 index.html abc.txt xyz.txt
Total files = 7

It is a very simple Java that displays files and directories in the given directory. It doesn’t tell which one is file or directory. And it doesn’t show files inside subdirectories. It doesn’t display the correct result when we pass “abc.txt” which is a file rather than a directory, or when the passed directory is empty.


Java program to get all files and directory

import java.io.File;

public class DisplayFiles {

   public static void main(String[] args) {

      int dirCount = 0;
      int fileCount = 0;

      File dir = new File("abc");
      File[] files = dir.listFiles();

      if(files == null) {
         System.out.println( dir + 
             " is not a directory");
      } else {

         for(File f: files){

            if(f.isFile()) {
               fileCount++;
               System.out.println( f + 
                         " is a file");

            } else if(f.isDirectory()) {
               dirCount++;
               System.out.println( f + 
                    " is a directory");
            }
         }

         System.out.println("Total file = " 
                               + fileCount );
         System.out.println("Total directory = " 
                                 + dirCount );
      }
   }
}

Output:-

TestFile/dir2 is a directory
TestFile/Hello.java is a file
TestFile/dir1 is a directory
TestFile/index.html is a file
TestFile/abc.txt is a file
Total file = 3
Total directory = 2

If we pass an empty directory then it display message,

Total file = 0
Total directory = 0

If we pass a file “test.java” as input then it displays,

abc.txt is not a directory

This Java program get list of files and directories, display name and their count inside a directory only, it doesn’t list the sub directories and their files. Now, let us develop it.


Java program to get the list of all files in directory and subdirectories

In the previous program, whenever sub-directory encounters then the program just reads the name and displays it, but this time program should go inside the subdirectory. In the subdirectory list all files and sub-sub-directories, and for those also go to those sub-sub-directories. It is a recursive problem, the program needs to do the same thing in the subdirectory which it done in the parent directory i.e. list the files, directories and go to inside the directories.

To solve this problem we should use the recursion technique. In the below program we define a recursive method listAndCount() which calls itself whenever it encounters a directory.

import java.io.File;
public class DisplayFiles {

   static int dirCount;
   static int fileCount;

   public static void main(String[] args) {

      File dir = new File("TestFile");
      listAndCount(dir);

      System.out.println("Total files = " 
                                + fileCount );
      System.out.println("Total directories = " 
                                + dirCount );
   }


   // recursive method
   public static void listAndCount(File dir) {

      File[] files = dir.listFiles();

      if(files == null) {
         System.out.println(dir + 
             " is not a directory");
      } else {

         for(File f: files){

            if(f.isFile()) {
               fileCount++;
               System.out.println( f + 
                         " is a file");

            } else if(f.isDirectory()) {
               dirCount++;
               System.out.println( f + 
                    " is a directory");

               // go to inside the directory
               listAndCount(f);
            }
         }
      }
   }
}

Output:-

TestFile/dir2 is a directory
TestFile/dir2/dir23 is a directory
TestFile/dir2/dir21 is a directory
TestFile/dir2/dir21/abc211.txt is a file
TestFile/dir2/dir22 is a directory
TestFile/dir2/dir22/dir221 is a directory
TestFile/dir2/dir22/abc2211.pdf is a file
TestFile/Hello.java is a file
TestFile/dir1 is a directory
TestFile/dir1/abc11.txt is a file
TestFile/dir1/dir11 is a directory
TestFile/dir1/dir11/abc111.txt is a file
TestFile/dir1/dir11/abc112.java is a file
TestFile/dir1/dir12 is a directory
TestFile/index.html is a file
TestFile/abc.txt is a file
Total files = 8
Total directories = 8

When we pass “abc.txt” which is a file, rather than a directory then it displays,

abc.txt is not a directory
Total file = 0
Total directory = 0

When we pass an empty directory then it displays,

Total files = 0
Total directories = 0


Get of files based on an extension

In TestFile,

  • abc.txt
  • Hello.java
  • index.html
  • xyz.txt
  • input.txt

In the “TestFile” directory there are multiple .txt files are there. Let us develop a program to display all files having a particular extension in the directory.

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

class FileExtension implements FilenameFilter {

   String extFile;

   public FileExtension(String extFile) {
      this.extFile = "."+extFile;
   }

   public boolean accept(File dir, String name) {
      return name.endsWith(extFile);
   }
}


public class DisplayFiles {

   public static void main(String[] args) {
      File dir = new File("TestFile");

      if(dir.isFile()) {
         System.out.println(dir + " is a file.");
         return;
      }

      String extension = "txt";
      FilenameFilter onlyFile = new FileExtension(extension);

      String[] strFile = dir.list(onlyFile);
      System.out.println("The files in "+ dir + 
             " with ."+ extension +" extension are : ");

      for(String s: strFile) {
         System.out.print(s +"  ");
      }

      System.out.println("\nTotal files = " + strFile.length);
   }
}

Output:-

The files in TestFile with .txt extension are :
input.txt abc.txt xyz.txt
Total files = 3

If you enjoyed this post, share it with your friends. Do you want to share more information about the topic discussed above or do you find anything incorrect? Let us know in the comments. Thank you!

Leave a Comment

Your email address will not be published. Required fields are marked *