利用正则表达式统计代码数量--简易版



package com.zcj.javase.regex;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.io.Reader;

/**
 * 统计某个文件夹下代码数量
 *
 * @author cj_zu
 *
 */
public class regex2 {
 private static long normalLines = 0;
 private static long commentLines = 0;
 private static long whiteLines = 0;

 /**
  * @param args
  */
 public static void main(String[] args) {
  // TODO Auto-generated method stub
  File file = new File("F:\\Code\\work\\project\\src");
  statistics(file);
  System.out.println("空白行有:" + whiteLines);
  System.out.println("注释行有:" + commentLines);
  System.out.println("代码行有:" + normalLines);
 }

 public static void statistics(File file) {
  if (null == file) {
   return;
  }
  File[] codeFiles = file.listFiles();
  if (null == codeFiles || codeFiles.length == 0) {
   return;
  }
  System.out.println(file.getAbsolutePath() + " 文件目录包含 "
    + codeFiles.length + " 个文件");

  for (File f : codeFiles) {
   if (f.isDirectory()) {
    statistics(f);
   } else {
    if (f.getAbsolutePath().matches(".*\\.java$")) {
     System.out.println(f.getAbsolutePath());
     parse(f);
    }
   }
  }
 }

 public static void parse(File file) {
  BufferedReader bufferedReader = null;
  boolean comment = false;
  try {
   bufferedReader = new BufferedReader(new FileReader(file));
   String line;
   while (null != (line = bufferedReader.readLine())) {
    if (null != line && "" != line) {
     // 如果以零个或者若干个空白字符开头并结尾,则为空白行
     if (line.matches("^[\\s&&[^\\n]]*$")) {
      whiteLines++;
      // 如果以零个或者若干个空白字符 + “/*” 开头, 且不是以“*/”结束,则为注释行(并标记为注释行开始)
     } else if (line.matches("^[\\s]*/\\*")
       && !line.matches("\\*/$")) {
      commentLines++;
      comment = true;
     } else if (comment) {
      commentLines++;
      // 如果以 “*/” 结尾,则标记注释行结束
      if (line.matches("\\*/$")) {
       comment = false;
      }
      // 如果以零个或者若干个空白字符 + “//” 开头,则为注释行
     } else if (line.matches("^[\\s]*//")) {
      commentLines++;
      // 如果一行注释为“/* */”,则为注释行
     } else if (line.matches("^[\\s]*/\\*")
       && line.matches("\\*/$")) {
      commentLines++;
     } else {
      normalLines++;
     }
    }
   }
  } catch (Exception e) {
   e.printStackTrace();
  } finally {
   try {
    bufferedReader.close();
   } catch (IOException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
   }
  }
 }
}

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值