0

I m expecting to see a list of all files located under path d:/test folder. However, I can only get the files directly under that folder, but not recursively. Code:

        String folder = "D:/test";
        Path path = fs.getPath(folder);
        try (DirectoryStream<Path> directoryStream = Files.newDirectoryStream(path)) {  
            for (Path p : directoryStream) {
                System.out.println(p.getFileName());
            }
        } catch (IOException e) {  
            e.printStackTrace();  
        }

result:

a.txt
folder

folder structure: enter image description here

Tiina
  • 4,285
  • 7
  • 44
  • 73

3 Answers3

3

The Files::newDirectoryStream are meant to behave like that. If you want to recursively retrieve all directories and files in the given directory and its sub-directories, you will need Files::walk or Files::walkFileTree. For example (I assume you use Java 8):

Path path = //...
try {
    Files.walk(path).map(Path::getFileName).forEach(System.out::println);
} catch (IOException e) {
    e.printStackTrace();
}
glee8e
  • 6,180
  • 4
  • 31
  • 51
  • so I guess @Rambler's answer would be a "how to do it" in java 7? – Tiina May 27 '16 at 04:16
  • 1
    @Tiina Certainly. But beware that if your directory is very, very deep, or contains a loop (via symbolic/hard links), you will end up with an StackOverFlowExcepetion. If your software may work with unknown directory, you may need to modify how it works. – glee8e May 27 '16 at 04:40
3

Another way to this extending your own logic :

public static void printFileNamesRecursively(String path){
    Path yourPath = FileSystems.getDefault().getPath(path);

    try (DirectoryStream<Path> directoryStream = Files.newDirectoryStream(yourPath))           {  
            for (Path p : directoryStream) {
                System.out.println(p.getFileName());
                if(p.toFile().isDirectory()){

                    printFileNamesRecursively(p.toString());
                }

            }
        } catch (IOException e) {  
            e.printStackTrace();  
        }
}
Rambler
  • 4,994
  • 2
  • 20
  • 27
1

This is the right behavior for DirectoryStream. Instead, You can use org.apache.commons.io.FileUtils to enumerate the files recursively.

Shabbir Dhangot
  • 8,954
  • 10
  • 58
  • 80
Piyg
  • 224
  • 2
  • 10