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
    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);
    }
                        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...-
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With