NetBeans插件开发:如何获取当前打开项目中每个类的代码行数
嘿,我刚好做过类似的NetBeans插件开发,给你梳理下获取Java项目中每个类代码行数的具体实现方案,都是基于NetBeans官方API来做的,靠谱又省心:
第一步:获取当前激活的项目
首先得拿到用户当前正在操作的项目,NetBeans提供了OpenProjects类来访问已打开的项目,比如获取主项目:
Project currentProject = OpenProjects.getDefault().getMainProject(); if (currentProject == null) { // 这里可以给用户弹个提示,说没有打开的项目 return; }
第二步:定位Java源文件
接下来要找到项目里所有的Java源文件,用JavaSources API可以轻松获取项目的Java源根,避免自己手动遍历文件系统的麻烦:
JavaSources javaSources = JavaSources.forProject(currentProject); if (javaSources == null) { // 说明当前不是Java项目,提示用户即可 return; }
然后遍历所有Java源组里的文件,用FileUtil.visitFile递归遍历每个源根下的文件:
javaSources.getSourceGroups(JavaProjectConstants.SOURCES_TYPE_JAVA).forEach(sourceGroup -> { FileObject rootFolder = sourceGroup.getRootFolder(); try { FileUtil.visitFile(rootFolder, new FileVisitor() { @Override public FileVisitResult visitFile(FileObject file, IOException exc) throws IOException { // 只处理Java文件 if ("text/x-java".equals(file.getMIMEType())) { // 统计行数并记录 int totalLines = countTotalLines(file); int effectiveLines = countEffectiveLines(file); // 可选:统计有效代码行 System.out.println(String.format("%s: 总行数%d,有效代码行%d", file.getPath(), totalLines, effectiveLines)); } return FileVisitResult.CONTINUE; } // 实现其他FileVisitor方法,默认返回CONTINUE即可 @Override public FileVisitResult visitFileFailed(FileObject file, IOException exc) throws IOException { return FileVisitResult.CONTINUE; } @Override public FileVisitResult preVisitDirectory(FileObject dir, IOException exc) throws IOException { return FileVisitResult.CONTINUE; } @Override public FileVisitResult postVisitDirectory(FileObject dir, IOException exc) throws IOException { return FileVisitResult.CONTINUE; } }); } catch (IOException e) { Exceptions.printStackTrace(e); } });
第三步:实现行数统计逻辑
这里提供两个版本的统计方法:
统计总行数(包含空行和注释)
这个很简单,直接读取文件的每一行计数:
private int countTotalLines(FileObject file) throws IOException { try (BufferedReader reader = new BufferedReader(file.getReader())) { int lineCount = 0; while (reader.readLine() != null) { lineCount++; } return lineCount; } }
统计有效代码行(排除空行和注释)
如果需要更精准的统计,可以过滤掉空行和注释:
private int countEffectiveLines(FileObject file) throws IOException { try (BufferedReader reader = new BufferedReader(file.getReader())) { int effectiveCount = 0; boolean inMultiLineComment = false; String line; while ((line = reader.readLine()) != null) { line = line.trim(); // 跳过空行 if (line.isEmpty()) continue; // 处理多行注释 if (inMultiLineComment) { if (line.endsWith("*/")) { inMultiLineComment = false; } continue; } if (line.startsWith("/*")) { inMultiLineComment = true; if (line.endsWith("*/")) { inMultiLineComment = false; } continue; } // 跳过单行注释 if (line.startsWith("//")) continue; // 剩下的就是有效代码行 effectiveCount++; } return effectiveCount; } }
最后注意事项
- 要在插件的
module.xml里引入必要的模块依赖:比如org.netbeans.api.projects、org.netbeans.api.java.source、org.openide.filesystems、org.openide.util这些,不然编译会报错。 - 把这些逻辑放到你的插件按钮的
Action实现里,点击按钮时触发统计,然后把结果展示到弹出窗口里就可以了。
这样应该就能满足你的需求啦,亲测有效哦!
内容的提问来源于stack exchange,提问作者undisp
相关产品推荐
相关产品推荐

