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();
}
}