源码如下:
import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
public class TextCountDir {
private int count;
/**
* 统计一个java文件的行数
* @throws IOException
*/
private void countLine(File sourceFile) throws IOException {
BufferedReader br =null;
try {
br = new BufferedReader(new FileReader(sourceFile));
while (br.readLine()!=null) {
count++;
}
} catch (FileNotFoundException e) {
e.printStackTrace();
}finally {
br.close();
}
}
/**
* 统计一个目录下所有java文件的行数
* @throws IOException
*/
private void countDir(String sourceDir) throws IOException {
//检查源目录
File fSourceDir = new File(sourceDir);
if (!fSourceDir.exists()||!fSourceDir.isDirectory()) {
System.out.println("源目录不存在");
return;
}
//遍历目录下的文件或目录
File[] file =fSourceDir.listFiles();
for (int i = 0; i < file.length; i++) {
if (file[i].isFile()) {
if (file[i].getName().toLowerCase().endsWith("java")) {
//System.out.println(file[i].getName());
countLine(file[i]);
}
}
//递归统计代码行数
if (file[i].isDirectory()) {
//准备统计的文件夹
String subSourceDir = sourceDir + File.separator + file[i].getName();
//统计子目录
countDir(subSourceDir);
}
}
}
public static void main(String[] args) throws IOException {
TextCountDir tcd = new TextCountDir();
tcd.countDir("d:eclipse-workspace");
System.out.println(tcd.count);
}
}