贴个自己的代码可以统计指定目录或文件的行数,不统计空行,但是统计注释。
import java.io.*;
import java.util.*;
public class LineCounts{
public LineCounts(){
}
public int getAllLineCounts(File dir){
if(!dir.isDirectory()){
return getLineCounts(dir);
}
File[] fileLists = dir.listFiles();
int count = 0;
for(int i = 0 ;i < fileLists.length; i ++){
File file = fileLists[i];
if(file.isDirectory()){
System.out.println("Directory: " + file.getName());
int currentCount = getAllLineCounts(file);
count = count + currentCount;
System.out.println("目录"+ file.getName() + "共" + currentCount + "行\n");
}else{
System.out.print("File name: " + file.getName());
int currentCount = getLineCounts(file);
count = count + currentCount;
System.out.println(" " + currentCount + "行");
}
}
return count;
}
public int getLineCounts(File file){
int count = 0;
try{
BufferedReader in = new BufferedReader(new FileReader(file));
String line;
while((line = in.readLine()) != null){
if(!line.equals("") ){
count ++;
}
}
}catch(FileNotFoundException e){
e.printStackTrace();
}catch(IOException e){
e.printStackTrace();
}
return count;
}
public static void main(String[] args){
File dir = new File(args[0]);
LineCounts lc = new LineCounts();
int count = lc.getAllLineCounts(dir);
System.out.println("共 " + count + " 行");
}
}
使用截图: