您的位置:首页 > 编程语言 > Java开发

java实现统计代码行数

2013-05-03 21:42 639 查看
贴个自己的代码可以统计指定目录或文件的行数,不统计空行,但是统计注释。

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 + " 行");
}
}
使用截图:

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: