Java正则表达式(三)、代码量统计工具(统计java源文件中注释、代码、空白行数量)(二)

2014-11-24 08:34:34 · 作者: · 浏览: 4
Pattern blankLinePattern = Pattern.compile("^\\s*$"); // 空白行匹配器(匹配回车、tab键、空格)

Pattern codeLinePattern = Pattern.compile("( !import|package).+;\\s*(((//)|(/\\*+)).*)*",
Pattern.MULTILINE + Pattern.DOTALL); // 代码行匹配器(以分号结束为一行有效语句,但不包括import和package语句)

// 遍历文件中的每一行,并根据正则匹配的结果记录每一行匹配的结果
String line = null;
try {
while((line = bufr.readLine()) != null) {
if (annotationLinePattern.matcher(line).find()) {
annotationLine ++;
}

if (blankLinePattern.matcher(line).find()) {
blankLine ++;
}

if (codeLinePattern.matcher(line).matches()) {
codeLine ++;
}

totalLine ++;
}

} catch (IOException e) {
throw new RuntimeException("读取文件失败!" + e);
} finally {
try {
bufr.close(); // 关闭文件输入流并释放系统资源
} catch (IOException e) {
throw new RuntimeException("关闭文件输入流失败!");
}
}
}
}
}
测试结果:

作者:xyang81