Java - 从文件中读取包和 Class 名称

Java - Read package and Class name from file

我正在尝试从文件中读取包和 class 名称。在下面的代码中 fileEntry.getName() 给我输出 C:User\mywork\Myproject\target\generated-source\java\demo\Project.java。我只想得到 demo.Project 作为输出。感谢建议谢谢

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

        }
    }
}

我想你只需要找到 java class 个文件并且你想要声明为 package1.package2.demo.Project 的内部包。您可以进行一些字符串操作来获得该输出。

public static String FILE_SEPARATOR = System.getProperty("file.separator");

public static void listFilesForFolder(final File folder) {
    for (final File fileEntry : folder.listFiles()) {
        if (fileEntry.isDirectory()) {
            listFilesForFolder(fileEntry);
        } else {
            if (!fileEntry.getName().endsWith(".java")) {
                continue;
            }
            String absolutePath = fileEntry.getAbsolutePath();
            String javaPackageSeparator = FILE_SEPARATOR + "java" + FILE_SEPARATOR;
            int indexOf = absolutePath.indexOf(javaPackageSeparator);
            if (indexOf > -1) {
                String javaFilePath = absolutePath.substring(indexOf, absolutePath.length());
                String strippedJavaSeparator = javaFilePath.replace(javaPackageSeparator, "");
                String[] constructProperPackageName = strippedJavaSeparator.split(Pattern.quote(FILE_SEPARATOR));
                String packageName = "";
                String className = "";
                for (int i = 0; i < constructProperPackageName.length; i++) {
                    if (i == constructProperPackageName.length - 1) {
                        className = constructProperPackageName[i].replace(".java", "");
                        continue;
                    }
                    packageName += constructProperPackageName[i] + ".";
                }
                System.out.println(packageName + className);
            }
        }
    }
}

产生如下输出:

com.company.exception.handler.AbstractExceptionHandler
com.company.exception.handler.IExceptionHandler
com.company.exception.handler.APIRequestExceptionHandler
...

使用Files.find 对根/源目录进行简单扫描将return 所有java 文件,然后您可以调整路径以生成包名称。

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);
}