How to display all the files in a directory using Java



Problem Description

How to display all the files in a directory?

Solution

Following example shows how to display all the files contained in a directory using list method of File class.

import java.io.*;

public class Main {
   public static void main(String[] args) {
      File dir = new File("C:");
      String[] children = dir.list();
      
      if (children == null) {
         System.out.println( "Either dir does not exist or is not a directory");
      } else { 
         for (int i = 0; i< children.length; i++) {
            String filename = children[i];
            System.out.println(filename);
         }
      }
   }
}

Result

The above code sample will produce the following result.

build
build.xml
destnfile
detnfile
filename
manifest.mf
nbproject
outfilename
src
srcfile
test

The following is an another example to display all the files in a directory.

import java.io.File;

public class ReadFiles { 
   public static File folder = new File("C:\\Apache24\\htdocs");
   static String temp = "";
   
   public static void main(String[] args) {
      System.out.println("Reading files under the folder "+ folder.getAbsolutePath());
      listFilesForFolder(folder);
   } 
   public static void listFilesForFolder(final File folder) {
      for (final File fileEntry : folder.listFiles()) {
         if (fileEntry.isDirectory()) {
            listFilesForFolder(fileEntry);
         } else {
            if (fileEntry.isFile()) {
               temp = fileEntry.getName();
               if ((temp.substring(temp.lastIndexOf('.') 
                  + 1, temp.length()).toLowerCase()).equals("txt"))System.out.println(
                  "File = " + folder.getAbsolutePath()+ "\\" + fileEntry.getName());
            } 
         } 
      } 
   }
}

The above code sample will produce the following result.

Reading files under the folder C:\Apache24\htdocs
File= C:\Apache24\htdocs\android\bkp\end.txt
File= C:\Apache24\htdocs\android\end.txt
File= C:\Apache24\htdocs\cpp_standard_library\images\code.txt
File= C:\Apache24\htdocs\java\Java - Data Structures.txt
File= C:\Apache24\htdocs\java\Java - Inheritance.txt
File= C:\Apache24\htdocs\scripts\easyui\changelog.txt
java_directories.htm
Advertisements