基于[心系代码]文章的二次开发(https://blog.csdn.net/java_study_/article/details/129851977)
用于统计文件的行数和大小
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.util.regex.Pattern;
/**
* @author zbg
* @date 2023/11/30 14:36
*/
public class CodeLineCounter {
// 匹配注释行的正则表达式
private static final Pattern COMMENT_PATTERN = Pattern.compile("^(\\s*//|/\\*|\\*/|\\s*\\*)");
// 匹配空行的正则表达式
private static final Pattern BLANK_PATTERN = Pattern.compile("^\\s*$");
public static void main(String[] args) {
File projectDir = new File("D:\\workspace-idea\\demo");
// 统计文件名包含User的java文件的代码数及文件大小(B)
long[] counter = countLines(projectDir, ".java", true, "User");
System.out.println("Total lines of code: " + counter[0] + "\t " + "Total sizes of code: " + counter[1] + " B");
}
/**
* 递归统计目录或文件的行数及大小
* file: 目录
* suffix: 后缀
* contain: 是否模糊匹配文件名
* keyword: 模糊匹配文件名
*/
private static long[] countLines(File file, String suffix, boolean contain, String keyword) {
if (file.isDirectory()) {
long lineCount = 0;
long sizeCount = 0;
for (File subFile : file.listFiles()) {
long[] counter = countLines(subFile, suffix, contain, keyword);
lineCount += counter[0];
sizeCount += counter[1];
//lineCount += countLines(subFile, suffix, contain, keyword);
}
long[] ret = {lineCount, sizeCount};
return ret;
} else {
if (file.getName().endsWith(suffix)) {
if(!contain) {
return singleResult(file);
} else {
if(file.getName().contains(keyword)) {
return singleResult(file);
} else {
long[] ret = {0, 0};
return ret;
}
}
} else {
long[] ret = {0, 0};
return ret;
}
}
}
/**
* 单个文件结果
* @return
*/
private static long[] singleResult(File file) {
long line = countLinesInFile(file);
long size = file.length();
System.out.println(file.getPath() + "\t" + line + "\t" + size);
long[] ret = {line, size};
return ret;
}
/**
* 统计单个Java源代码文件的行数
*/
private static long countLinesInFile(File file) {
long lineCount = 0;
try (BufferedReader reader = new BufferedReader(new FileReader(file))) {
String line;
while ((line = reader.readLine()) != null) {
if (!isCommentOrBlank(line)) {
lineCount++;
}
}
} catch (IOException e) {
e.printStackTrace();
}
return lineCount;
}
/**
* 判断是否是注释行或空行
*/
private static boolean isCommentOrBlank(String line) {
return COMMENT_PATTERN.matcher(line).find() || BLANK_PATTERN.matcher(line).find();
}
}