Search code examples
javadirectorysubdirectory

Java- Recursively Get the path of directorys with files on it


How do i recursively get the path of directorys with files on it?

Im writing a program that needs to get the path of all the directories with JAVA files on it, recursively, for example:

|   |-->Foo2 --> lore.java
|Foo|
|   |-->Foo3 --> Foo4 --> ipsum.java

In this example, I would want to save in a list: FOO/FOO2 and FOO/FOO3/FOO4. There may be more nested directories, and those directories might contain java files, an example might be:

|
|   |--> Foo2 --> lore.java
|   |
|Foo|         | --> ipsum.java
|   |--> Foo3 |
|   |         | --> Foo4 --> rosae.java

In this example, i would want to save FOO/FOO2, FOO/FOO3 and FOO/FOO3/FOO4. Any ideas? Thanks!


Solution

  • See if the following will work for you:

    public static void main(String[] args) {
    
            List<Path> listOfDirectoryPaths = new ArrayList<>();
    
            try (Stream<Path> walk = Files.walk(Paths.get("."))) {
                walk.forEach(path -> {
                    if(path.toFile().isFile() && path.toFile().getName().contains(".java")) {
                        listOfDirectoryPaths.add(path.getParent());
                    }
                });
    
            } catch (IOException e) {
                e.printStackTrace();
            }
            System.out.println(listOfDirectoryPaths.stream().distinct().collect(Collectors.toList()));
        }
    }
    

    This will traverse the current directory (.) of where you run it from. It will look for files that contain ".java" It will store the Path of the Dir. Finally, it will return only the distinct paths, so you dont get duplicates.

    Try it, and modify it as you see fit.