http://blog.youkuaiyun.com/suwanjun881011/article/details/4475967
- importjava.io.BufferedReader;
- importjava.io.File;
- importjava.io.FileNotFoundException;
- importjava.io.FileReader;
- importjava.io.IOException;
- /**
- *
- *@authorjun
- *
- */
- publicclassSumJavaCode{
- staticlongnormalLines=0;//空行
- staticlongcommentLines=0;//注释行
- staticlongwhiteLines=0;//代码行
- publicstaticvoidmain(String[]args){
- SumJavaCodesjc=newSumJavaCode();
- Filef=newFile("D://spring-framework-2.0-with-dependencies//spring-framework-2.0");
- System.out.println(f.getName());
- sjc.treeFile(f);
- System.out.println("空行:"+normalLines);
- System.out.println("注释行:"+commentLines);
- System.out.println("代码行:"+whiteLines);
- }
- /**
- *查找出一个目录下所有的.java文件
- *
- *@paramf要查找的目录
- */
- privatevoidtreeFile(Filef){
- File[]childs=f.listFiles();
- //intcount=0;
- //intsum=0;
- for(inti=0;i<childs.length;i++){
- //System.out.println(preStr+childs[i].getName());
- if(!childs[i].isDirectory()){
- if(childs[i].getName().matches(".*//.java$")){
- System.out.println(childs[i].getName());
- //count++;
- sumCode(childs[i]);
- }
- }else{
- treeFile(childs[i]);
- //sum+=count;
- }
- }
- }
- /**
- *计算一个.java文件中的代码行,空行,注释行
- *
- *@paramfile
- *要计算的.java文件
- */
- privatevoidsumCode(Filefile){
- BufferedReaderbr=null;
- booleancomment=false;
- try{
- br=newBufferedReader(newFileReader(file));
- Stringline="";
- try{
- while((line=br.readLine())!=null){
- line=line.trim();
- if(line.matches("^[//s&&[^//n]]*$")){
- whiteLines++;
- }elseif(line.startsWith("/*")&&!line.endsWith("*/")){
- commentLines++;
- comment=true;
- }elseif(true==comment){
- commentLines++;
- if(line.endsWith("*/")){
- comment=false;
- }
- }elseif(line.startsWith("//")){
- commentLines++;
- }else{
- normalLines++;
- }
- }
- }catch(IOExceptione){
- e.printStackTrace();
- }
- }catch(FileNotFoundExceptione){
- e.printStackTrace();
- }finally{
- if(br!=null){
- try{
- br.close();
- br=null;
- }catch(IOExceptione){
- e.printStackTrace();
- }
- }
- }
- }
- }