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 );
}
long countLines(String dir, List<String> suffixIncludes, List<String> subStringExcludes) {
String directoryPath = dir;
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();
}
}
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步