package com.ed.core.util;
import java.io.*;
/**
* @ProjectName: gitIdeaWork
* @Package: com.ed.core.util
* @ClassName: CodeLineStatisticsTest
* @Author:
* @Description:
* @Date: 2019/12/26 17:03
* @Version: 1.0
*/
public class CodeLineStatisticsTest {
private static int normalLines = 0; //有效程序行數
private static int whiteLines = 0; //空白行數
private static int commentLines = 0; //註釋行數
public static void countCodeLine(File file) {
System.out.println("代碼行數統計:" + file.getAbsolutePath());
if (file.exists()) {
try {
scanFile(file);
} catch (IOException e) {
e.printStackTrace();
}
} else {
System.out.println("文件不存在!");
System.exit(0);
}
System.out.println(file.getAbsolutePath() + " ,java文件統計:" +
"總有效代碼行數: " + normalLines +
" ,總空白行數:" + whiteLines +
" ,總註釋行數:" + commentLines +
" ,總行數:" + (normalLines + whiteLines + commentLines));
}
private static void scanFile(File file) throws IOException {
if (file.isDirectory()) {
File[] files = file.listFiles();
for (int i = 0; i < files.length; i++) {
scanFile(files[i]);
}
}
if (file.isFile()) {
count(file);
}
}
private static void count(File file) {
BufferedReader br = null;
// 判斷此行是否爲註釋行
boolean comment = false;
int temp_whiteLines = 0;
int temp_commentLines = 0;
int temp_normalLines = 0;
try {
br = new BufferedReader(new FileReader(file));
String line = "";
while ((line = br.readLine()) != null) {
line = line.trim();
if (line.matches("^[//s&&[^//n]]*$")) {
// 空行
whiteLines++;
temp_whiteLines++;
} else if (line.startsWith("/*") && !line.endsWith("*/")) {
// 判斷此行爲"/*"開頭的註釋行
commentLines++;
comment = true;
} else if (comment == true && !line.endsWith("*/")) {
// 爲多行註釋中的一行(不是開頭和結尾)
commentLines++;
temp_commentLines++;
} else if (comment == true && line.endsWith("*/")) {
// 爲多行註釋的結束行
commentLines++;
temp_commentLines++;
comment = false;
} else if (line.startsWith("//")) {
// 單行註釋行
commentLines++;
temp_commentLines++;
} else {
// 正常代碼行
normalLines++;
temp_normalLines++;
}
}
System.out.println(file.getName() +
" ,有效行數" + temp_normalLines +
" ,空白行數" + temp_whiteLines +
" ,註釋行數" + temp_commentLines +
" ,總行數" + (temp_normalLines + temp_whiteLines + temp_commentLines));
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
if (br != null) {
try {
br.close();
br = null;
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
//測試
public static void main(String[] args) {
File file = new File("C:\\Users\\Desktop\\CodeLineStatisticsTest.java");
countCodeLine(file);
}
}
統計某一個文件中有總行數、效行數、空白行數、註釋行數
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.