0

I have a folder structure like : E:\Test. Inside it I have many sub-folders like FolderA, FolderB, FolderC, etc.

I want to have a java program that will list down all the subfolders and the report files inside the subfolders. How can I achieve this? Using the below snippet, I can access the different folders inside the E:\Test directory, but files inside the subfolders aren't appearing.

 public static void main(String args[]){
    File directoryPath = new File("E:\\Test\\");

    File folderPath [] = directoryPath.listFiles(); 
    System.out.println("List of files and folders in the directory :  ");
    for(File file : folderPath){
        System.out.println("Folder Name Is : " +file.getAbsolutePath());
        System.out.println("Files under the folderpath are : " +file.listFiles());
        System.out.println(" " );
    }
    
}
Mark Rotteveel
  • 100,966
  • 191
  • 140
  • 197
Cris-123
  • 28
  • 5
  • 1
    You need to use recursion. Write a method (let's say `listContent(File)`) that prints out the content of a directory. Each time one of the files in a directory is itself a Directory, it just calls itself again. – Joachim Sauer Sep 02 '20 at 08:57
  • use recursion and pass the folder to the method untill u get a file – Amit Kumar Lal Sep 02 '20 at 09:01
  • What about `java.nio` and [walking the file tree](https://docs.oracle.com/javase/tutorial/essential/io/walk.html)? – deHaar Sep 02 '20 at 09:05

1 Answers1

0
import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;

public class Main {

    private static final StringBuilder tabs = new StringBuilder();

    public static void main(String[] args) {
        try {
            Path start = new File("E:\\Test\\").toPath();
            System.out.println("List of files and folders in the directory " + start.getFileName() + ": ");
            Files.walk(start).forEach(Main::printInfo);
        } catch (IOException ignore) {
        }
    }

    public static void printInfo(Path path) {
        String tabs = Main.tabs.toString();
        if (Files.isDirectory(path)) {
            System.out.println(tabs + "Folder Name Is : " + path.getFileName());
            System.out.println(tabs + "Files under the " + path.toString() + ": ");
            Main.tabs.append("\t");
        } else {
            System.out.println(tabs + path.getFileName());
        }
    }
}
Volodya Lombrozo
  • 2,325
  • 2
  • 16
  • 34