用java语言编程统计程序的行数

import java.io.*; //代码统计(正规代码写法,也就是代码后面带注解只是按代码行算) public class CodeCounter { static long normalLines = 0L; // 正常行数 static long commentLines = 0L;// 注释行 static long whiteLines = 0L;// 空行 public static void main(String[] args) { File f = new File("G:\\A\\codeCounter\\"); File[] codeFiles = f.listFiles();// 找到这个文件夹所有的子文件 // System.out.println(f.getName());//查看找到那个文件 for (File child : codeFiles) { // 子文件夹的循环,都在同一个目录下 if (child.getName().matches(".*\\.java$")) { // 正则表达式判断以.java后缀名结尾的文件 parse(child); } } System.out.println("normalLines:" + normalLines); System.out.println("commentLines:" + commentLines); System.out.println("whiteLines:" + whiteLines); } private static void parse(File child) { BufferedReader br = null; // 读取文件创建有效的缓冲字符 boolean comment = false; // 代表注释里面的内容 try { br = new BufferedReader(new FileReader(child)); String line = ""; while ((line = br.readLine()) != null) { line=line.trim(); //就是去左右空格,然后返回一个字符串对象的拷贝 if (line.matches("^[\\s&&[^\\n]]*$")) { // 用正则表达式来匹配空行,[^\\n]表示非换行符 whiteLines++; } else if (line.startsWith("/*") && !line.endsWith("*/")) { // 以这个开头的,即注解的开始,并且不是以这个结尾 commentLines++; comment = true;// 说明注释开始 }else if(line.startsWith("/*") && line.endsWith("*/")){ //本身就是注释行的 commentLines++; } else if (true == comment) { commentLines++; if (line.endsWith("*/")) { comment = false; // 注释行到此结束了 } } else if (line.startsWith("//")) { commentLines++; } else { normalLines++; } } } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } finally { if (br != null) { try { br.close(); br = null; } catch (IOException e) { e.printStackTrace(); } } } } }

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值