正则表达试代码统计小工具

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

public class Code {
static long normalLines = 0;//代码
static long commentLines = 0;//注释
static long whiteLines = 0;
static boolean comment = false;

public static void main(String[] args) throws IOException {
ListFilesInDirectory("要统计的文件夹的路径");
System.out.println("代码normalLines= " + normalLines);
System.out.println("注释commentLines= " + commentLines);
System.out.println("空行whiteLines= " + whiteLines);
}

static void ListFilesInDirectory(String path) throws IOException {
File file = new File(path);
File[] files = file.listFiles();
for (File fl : files) {
if (fl.isDirectory())
ListFilesInDirectory(fl.toString());
else if (fl.getName().matches(".*\\.java$")) {
parse(fl);
}
}
}

private static void parse(File f) throws IOException {
BufferedReader br = null;
br = new BufferedReader(new FileReader(f));
String line = "";
while ((line = br.readLine()) != null) {
line = line.trim();
if (line.matches("^[\\s&&[^\\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++;
}
}
if (br != null) {
br.close();
br = null;
}
}
}

猜你喜欢

转载自doublecqw.iteye.com/blog/1173110