'Java - Read package and Class name from file

I am trying to read package and class name from file. In the below code fileEntry.getName() is giving me output C:User\mywork\Myproject\target\generated-source\java\demo\Project.java. I want to get only demo.Project as an output. Appreciate suggestion thank you

public void listFilesForFolder(final File folder) {
    for (final File fileEntry : folder.listFiles()) {
        if (fileEntry.isDirectory()) {
            listFilesForFolder(fileEntry);
        } else {
            System.out.println(fileEntry.getName());
            //C:User\mywork\Myproject\target\generated-source\java\demo\Project.java

        }
    }
}


Solution 1:[1]

A simple scan across the root / source directory using Files.find will return all java files, and then you can adjust the path to generate package name.

Path srcDir = Path.of("src");
BiPredicate<Path, BasicFileAttributes> dotjava = (p,a) -> a.isRegularFile() && p.getFileName().toString().endsWith(".java");
try(var java = Files.find(srcDir, Integer.MAX_VALUE, dotjava)) {
    java.map(p -> srcDir.relativize(p).toString().replaceAll("\\.java$", "").replace(File.separator, "."))
        .forEach(System.out::println);
}

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 DuncG