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();
}
}
}
}