public class FileLineCountTest {
/**
* 统计项目代码行数
*/
@Test
void projectLineCount() {
long count = countLines("D:\\Users\\guest\\IdeaProjects\\hello", List.of(".java", ".xml", ".sql"),
long count2 = countLines("D:\\gitlab_source\\hello-h5", List.of(".vue", ".js", ".html"), List.of("node_modules", "dist"));
System.out.println("hello: " + count );
System.out.println("hello-h5: " + count2 );
}
/**
* 统计指定目录下的源代码有多少行
*
* @param dir 目录
* @param suffixIncludes 要统计行数的文件后缀
* @param subStringExcludes 不统计文件路径里含有特定的字符串
* @return 该目录下所有符合统计规则的文件的行数
*/
long countLines(String dir, List<String> suffixIncludes, List<String> subStringExcludes) {
// 指定要遍历的目录路径
String directoryPath = dir;
// 创建Path对象
Path startPath = Paths.get(directoryPath);
// 原子长整型,用于累加所有文件的行数
AtomicLong totalLines = new AtomicLong(0);
// 遍历目录及其子目录
try {
Files.walkFileTree(startPath, new SimpleFileVisitor<Path>() {
@Override
public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {
// 读取文件的所有行,并累加行数
if (file.toFile().isFile()
&& suffixIncludes.stream().anyMatch(str -> file.toFile().getName().endsWith(str))
&& subStringExcludes.stream().noneMatch(str -> file.toFile().getAbsolutePath().contains(str))) {
long linesCount;
try {
linesCount = Files.lines(file).count();
totalLines.addAndGet(linesCount);
} catch (Exception e) {
System.out.println("path:" + file + ", error:" + e.getMessage());
}
}
return FileVisitResult.CONTINUE;
}
});
} catch (IOException e) {
e.printStackTrace();
}
// 输出总行数
System.out.println("总计包含 " + totalLines.get() + " 行。");
return totalLines.get();
}
}
标签:totalLines,代码,List,System,file,println,简易程序,统计,out
From: https://www.cnblogs.com/jiayuan2006/p/18336351