package temporary;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
public class ProjectLine {
List<File> fileList = new ArrayList<>(); //存放项目中所有文件和文件夹
int lineNumber = 0; //记录项目的总行数
public void countLines(String projectName) throws IOException {
//当前项目在工作空间下的位置
String path = System.getProperty("user.dir");
//修改为需要统计行数项目的位置,注意在同一工作目录下
path = path.substring(0, path.lastIndexOf("\\")+1) + projectName + "\\src";
System.out.println("path = " + path);
//读取当前目录src下的所有文件
File file = new File(path);
File[] files = file.listFiles();
//存放所有文件
addAllFiles(files);
//统计行数
readLines();
System.out.println("Project \"" + projectName + "\" has " + lineNumber + " lines!");
}
//判断是否为文件夹,如是,继续往下查找判断,并将所有的文件和文件夹存放到fileList中
public void addAllFiles(File[] files) {
for (File file : files) {
fileList.add(file);
// System.out.println(file.toString());
if (file.isDirectory()) {
files = file.listFiles();
addAllFiles(files);
continue;
}
}
}
//读取所有文件的行数
public void readLines() throws IOException {
FileReader fr = null;
BufferedReader br = null;
for (File file : fileList) {
int temp = lineNumber; //记录已经统计过的文件总行书,用于计算当前文件的行数
if (file.isDirectory()) {
continue; //判断为目录的则不参加计数
}
fr = new FileReader(file);
br = new BufferedReader(fr);
String line = "";
while ((line = br.readLine()) != null) {
if (!isBlankLine(line)) {
lineNumber++;
}
}
System.out.println(file.getName() + " has " + (lineNumber - temp) + " lines.");
}
fr.close();
br.close();
}
//判断是否为空行
public boolean isBlankLine(String line) {
if (line.trim().length() == 0)
return true;
return false;
}
public static void main(String[] args) throws IOException {
ProjectLine pl = new ProjectLine();
String projectName = "Blog";
pl.countLines(projectName);
}
}
//output~
path = C:\Documents and Settings\Administrator\workspace\Blog\src
Search.java has 12 lines.
AllSort.java has 124 lines.
BubbleSort.java has 43 lines.
HeapSort.java has 101 lines.
InsertSort.java has 57 lines.
MergeSort.java has 103 lines.
QuickSort.java has 56 lines.
SelectSort.java has 48 lines.
ProjectLine.java has 71 lines.
ProjectLines.java has 80 lines.
Soilder.java has 30 lines.
Project "Blog" has 725 lines!