1

I am building a program where the input is a directory path and the output should show all files in this path, including the files from a directory, which are in the given path. For example: Input: C: Output: C:/Directory1 and C:/Directory1/file1.pdf.

static string Directory = sc.next();
static File folder = new File(Directory);
static File[]listofFiles = folder.listFiles();

public static void ListOfFilesInADirectory (final File folder) {
for (int i = 0; i < listofFiles.length; i++) { 
              if (listofFiles[i].isFile()) {           
                System.out.println("File " + listofFiles[i].getName());
              } else if (listofFiles[i].isDirectory()) { 
                System.out.println("Directory " + listofFiles[i].getName());
              }
            }
    }

The code above is the code for the input of the directory and the output of all the files in this directory, but not them in a folder, of this directory. How can I show the files in folders of the director too?

Massin_NYC
  • 29
  • 1
  • 6

1 Answers1

1

It sounds like you want something like this...

\---folder
    |   file1.txt
    |   file2.txt
    |
    \---subfolder
            file3.txt
            file4.txt

To print...

folder\file1.txt
folder\file2.txt
folder\subfolder\file3.txt
folder\subfolder\file4.txt

If that assumption is right, one solution is to try using java.nio.file.Files.walk(Path).

Files.walk(Paths.get("folder"))
        .filter(Files::isRegularFile)
        .forEach(System.out::println);//print out the files in all directories from root

Files.walk(path) can return those subfolder files by walking the file tree rooted at the start file given.