Display all nested files at given directory location - Recursively display all files from innermost directories

In Java file.list() and file.listFiles() are used to list all File objects (file and directory) at given directory (All Files just one level down to that abstract file path). Suppose we want to list all nested files present at all level with respect to given abstract path.
Consider following E:\\Dir1\\file1.txt , E:\\Dir1\\Dir3\\file3.txt, E:\\Dir1\\file4.txt, E:\\Dir1\\file2.xml , E:\\Dir1\\temp.log - We want to list all files at E:\\Dir1. Output should be : file1.txt, file2.xml, file3.txt, file4.txt.
Below sample program display all files present below the given abstract path:-
package com.devinline.javaio;

import java.io.File;
import java.io.IOException;
import java.util.LinkedList;
import java.util.List;

public class DisplayAllNestedFiles {

 public static void main(String[] args) {
  List<File> fileList = new LinkedList<>();
  File dir = new File("E:\\input");
  fileList = listAllFiles(dir, fileList);
  // Display all files with absolute paths
  for (File file : fileList) {
   try {
    System.out.println(file.getCanonicalPath());
   } catch (IOException e) {
    e.printStackTrace();
   }
  }
 }

 // Recursive call to find File object is file or directory  
 private static List<File> listAllFiles(File dir, List<File> fileList) {
  for (File fileEntry : dir.listFiles()) {
   if (fileEntry.isDirectory()) {
    listAllFiles(fileEntry, fileList);
   } else {
    fileList.add(fileEntry);
   }
  }
  return fileList;
 }

}
======Sample Output========
E:\input\doc\Install_doc.doc
E:\input\EmployeeDST.xml
E:\input\extra\customerLog.json
E:\input\install_doc.pdf
E:\input\trailLog.json
========================
In above program, listAllFiles(File, List) method does looping on the given abstract path "E:\\input" and check if File object is Directory then again call this method again and if it is a file then add it to the list. Once this loop ends, list with all File object is returned and absolute path of each file is displayed.


1 Comments

Previous Post Next Post