Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java 8 : Get files from folder / subfolder [duplicate]

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

like image 434
Nunyet de Can Calçada Avatar asked Feb 01 '18 13:02

Nunyet de Can Calçada


2 Answers

    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);
    }
like image 164
Eugene Avatar answered Oct 22 '22 19:10

Eugene


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...-

like image 35
Dumbo Avatar answered Oct 22 '22 20:10

Dumbo