正则表达试代码统计小工具
import java.io.BufferedReader;
importjava.io.File;
importjava.io.FileReader;
importjava.io.IOException;
publicclassCode{
staticlongnormalLines=0;//代码
staticlongcommentLines=0;//注释
staticlongwhiteLines=0;
staticbooleancomment=false;
publicstaticvoidmain(String[]args)throwsIOException{
ListFilesInDirectory("要统计的文件夹的路径");
System.out.println("代码normalLines="+normalLines);
System.out.println("注释commentLines="+commentLines);
System.out.println("空行whiteLines="+whiteLines);
}
staticvoidListFilesInDirectory(Stringpath)throwsIOException{
Filefile=newFile(path);
File[]files=file.listFiles();
for(Filefl:files){
if(fl.isDirectory())
ListFilesInDirectory(fl.toString());
elseif(fl.getName().matches(".*\\.java$")){
parse(fl);
}
}
}
privatestaticvoidparse(Filef)throwsIOException{
BufferedReaderbr=null;
br=newBufferedReader(newFileReader(f));
Stringline="";
while((line=br.readLine())!=null){
line=line.trim();
if(line.matches("^[\\s&&[^\\n]]*$")){
whiteLines++;
}elseif(line.startsWith("/*")&&!line.endsWith("*/")){
commentLines++;
comment=true;
}elseif(line.startsWith("/*")&&line.endsWith("*/")){
commentLines++;
}elseif(true==comment){
commentLines++;
if(line.endsWith("*/")){
comment=false;
}
}elseif(line.startsWith("//")){
commentLines++;
}else{
normalLines++;
}
}
if(br!=null){
br.close();
br=null;
}
}
}