现在的位置: 首页 > 综合 > 正文

关于代码中空白、注释等字符的统计(正则表达式的使用)

2013年06月26日 ⁄ 综合 ⁄ 共 1367字 ⁄ 字号 评论关闭

 

public class test {
 static int normalLine = 0;
 static int whiteLine = 0;
 static int commentLine = 0;

 public static void main(String[] args) {
  File f = new File("E:\\java\\myworkspace\\game\\src");
  File[] l = f.listFiles();
  /*
   * for (int i = 0; i < l.length; ++i) { if
   * (l[i].getName().matches(".*\\.java$")) { parse(f); } }
   */
  for (File child : l) {
   System.out.println(child.getName());
   if (child.getName().matches(".*\\.java$")) {
    parse(child);
   }
  }
  System.out.println("normalLine共有:" + normalLine);
  System.out.println("whitelLine共有:" + whiteLine);
  System.out.println("commentLine共有:" + commentLine);

 }

 private static void parse(File f) {
  BufferedReader buf = null;
  boolean isComment = false;
  try {
   buf = new BufferedReader(new FileReader(f));
   String line = "";
   while ((line = buf.readLine()) != null) {
    line = line.trim();
    if (line.matches("^[\\s&&[^\\n]]*$")) {
     ++whiteLine;
    } else if (line.startsWith("/*") && line.endsWith("*/")) {
     ++commentLine;
    } else if (line.startsWith("/*") && !line.endsWith("*/")) {
     ++commentLine;
     isComment = true;
    } else if (true == isComment) {
     ++commentLine;
     if (line.endsWith("*/")) {
      isComment = false;
     }

    } else if (line.startsWith("//")) {
     ++commentLine;
    } else
     ++normalLine;
   }
  } catch (FileNotFoundException e) {
   // TODO Auto-generated catch block
   e.printStackTrace();
  } catch (IOException e) {
   // TODO Auto-generated catch block
   e.printStackTrace();
  }
 }

}

抱歉!评论已关闭.