java统计代码的行数,区别空行、注释行、代码行、配置行
package com.lxh.config.utils;
import java.io.*;
public class CountCodeLines {
private static long nullLines = 0;
private static long annoLines = 0;
private static long codeLines = 0;
private static long configLines = 0;
private static long allLines = 0;
public static void main(String[] args) {
CountCodeLines ccl = new CountCodeLines();
ccl.listFile("D:\\Java\\gitCode\\fire-command-platform-code");
System.out.println("空行:" + nullLines);
System.out.println("注释行:" + annoLines);
System.out.println("代码行:" + codeLines);
System.out.println("配置文件行:" + configLines);
System.out.println("总行:" + allLines);
}
private void listFile(String filePath) {
File f = new File(filePath);
File[] childs = f.listFiles();
for (int i = 0; i < childs.length; i++) {
if (!childs[i].isDirectory()) {
if (childs[i].getName().matches(".*\\.java$")
||childs[i].getName().endsWith(".yml")
|| childs[i].getName().endsWith(".xml")
) {
System.out.println(childs[i].getName());
sumCode(childs[i]);
}
}else {
listFile(childs[i].getPath());
}
}
}
private void sumCode(File file){
BufferedReader br = null;
try{
br = new BufferedReader(new FileReader(file));
String line = "";
while ((line = br.readLine()) != null){
allLines++;
if(file.getName().endsWith(".yml")
|| file.getName().endsWith(".xml")
|| file.getName().endsWith(".properties")){
configLines++;
}else {
String trimStr = line.trim();
if (trimStr.length() == 0){
nullLines++;
}else if (trimStr.startsWith("//")
|| trimStr.startsWith("/**")
|| trimStr.startsWith("*")
|| trimStr.startsWith("*/")
|| trimStr.startsWith("/*")
){
annoLines++;
}else {
codeLines++;
}
}
}
}catch (Exception e){
e.printStackTrace();
}finally {
try {
br.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}