package com.yonge.test;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
public class Test {
private static int commen, white, normal;
public Test() {
}
private static void countCode(File file) {
// 判断是否是.java结尾的文件
if (file.getName().matches(".*\\.java$")) {
FileReader fr = null;
BufferedReader br = null;
try {
fr = new FileReader(file);
br = new BufferedReader(fr);
String lineContent;
boolean isCommen = false;
try {
while (br.ready()) {
// 由于可能头存在空格,我们加trim()方法
lineContent = br.readLine().trim();
// 先判断注释行
if (lineContent.matches("^//.*")) {
commen++;
} else if (lineContent.matches("^/\\*.*")
&& !lineContent.matches(".*\\*/$")) {
commen++;
isCommen = true;
} else if (isCommen) {
commen++;
if (lineContent.matches(".*\\*/$")) {
isCommen = false;
}
} else if (lineContent.matches("^/\\*.*")
&& lineContent.matches(".*\\*/$")) {
commen++;
}
// 判断空白行
else if (lineContent.matches("^[\\s && [^\\n]]*$")) {
white++;
} else {
normal++;
}
}
} catch (IOException e) {
e.printStackTrace();
}
} catch (FileNotFoundException e) {
e.printStackTrace();
System.out.println("文件【" + file.getAbsolutePath() + "】不存在");
} finally {
if (br != null) {
try {
br.close();
if (fr != null) {
fr.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}
public static void main(String[] args) {
String filePath = "C:\\Users\\yonge\\workspace\\regex";
File file = new File(filePath);
File[] files = file.listFiles();
if (files != null && files.length > 0) {
for (File f : files) {
readDirectory(f);
}
}
System.out.println("空白行数:" + white);
System.out.println("注释行数:" + commen);
System.out.println("有效行数:" + normal);
}
/**
* 递归目录
* @param file
*/
private static void readDirectory(File file) {
if (file.isDirectory()) {
File[] files = file.listFiles();
for (File f : files) {
readDirectory(f);
}
} else {
countCode(file);
}
}
}