Java 8 : Get files from folder / subfolder

24,400

Solution 1

    Path configFilePath = FileSystems.getDefault()
            .getPath("C:\\Users\\sharmaat\\Desktop\\issue\\stores");

    List<Path> fileWithName = Files.walk(configFilePath)
            .filter(s -> s.toString().endsWith(".java"))
            .map(Path::getFileName).sorted().collect(Collectors.toList());

    for (Path name : fileWithName) {
        // printing the name of file in every sub folder
        System.out.println(name);
    }

Solution 2

Files.list(path) method returns only stream of files in directory. And the method listing is not recursive.
Instead of that you should use Files.walk(path). This method walks through all file tree rooted at a given starting directory.
More about it:
https://docs.oracle.com/javase/8/docs/api/java/nio/file/Files.html#walk-java.nio.file.Path-java.nio.file.FileVisitOption...-

Share:
24,400
Nunyet de Can Calçada
Author by

Nunyet de Can Calçada

no puedor, pecador de la pradera ! Ese peasso de Nullpointer que sale de la pantalla y me dise: Quietoooooor, que esto peta mas que una escopeta de feria, por la Gloria de mi Madre !!!! no puedo, no puedo, no puedo Ese peasso de Scrum ceremonias !!!! y que has hechor ? y que haras ??? y que hacees ?? y yo que sé, for my Mother's glory !!!!!!!! 7 Nullpointers que vienen de Bonaaansaaaa

Updated on July 23, 2022

Comments

  • Nunyet de Can Calçada
    Nunyet de Can Calçada almost 2 years

    I have this folders inside the resources folder of a SpringBoot app.

    resources/files/a.txt
    resources/files/b/b1.txt
    resources/files/b/b2.txt
    resources/files/c/c1.txt
    resources/files/c/c2.txt
    

    I want to get all the txt file, so this is my code:

       ClassLoader classLoader = this.getClass().getClassLoader();
       Path configFilePath = Paths.get(classLoader.getResource("files").toURI());   
    
       List<Path> atrackFileNames = Files.list(configFilePath)
                    .filter(s -> s.toString().endsWith(".txt"))
                    .map(Path::getFileName)
                    .sorted()
                    .collect(toList());
    

    But I only get the file a.txt