引用致谢: https://www.cnblogs.com/sdlzspl/p/7289816.html
package zhengze_35; import java.io.BufferedReader; import java.io.File; import java.io.FileReader; public class CalculateRow { public static void main(String[] args) { /* File file = new File("D:\\web\\zuoye\\src\\test\\CalculateRow.java") ; calculaterow(file) ;*/ File newfile = new File("d:/Eclipse_projects/Demo/src/zhengze_35/CalculateRow.java") ; calculateFile(newfile) ; File[] files = newfile.listFiles() ; /* for(File f: files){ System.out.println(f); }*/ /* int sum = 0 ; for (int i = 0; i < files.length; i++) { if(files[i].isDirectory()){ File[] filesi = files[i].listFiles() ; for (int j = 0; j < filesi.length; j++) { int num = calculaterow(filesi[j]); sum+=num ; } }else{ int num = calculaterow(files[i]); sum+= num ; } } System.out.println(newfile+"文件夹下的文件的代码行数总共有:"+sum);*/ } public static void calculateFile(File ff){ int sum =0 ; if(ff.isDirectory()){ File[] files = ff.listFiles() ; for(File f1: files){ if(f1.isDirectory()){ calculateFile(f1) ; }else{ int num =calculaterow(f1) ; sum +=num ; } } System.out.println(ff+"文件夹下的所有文件的代码行数总共:"+sum); }else if(ff.isFile()) { int num = calculaterow(ff) ; sum +=num ; System.out.println(ff+"文件下的所有文件的 代码行数总共:"+sum); }else{ System.err.println("输入的文件地址格式不对"); } } public static int calculaterow(File f){ int num= 0 ; if(f.isFile()){ try { BufferedReader br = new BufferedReader(new FileReader(f)) ; String str ; boolean flag = false ; while((str=br.readLine())!=null){ String newstr = str.trim() ; if(newstr.startsWith("/*")){ flag =true ; }else if (newstr.endsWith("*/")){ flag = false ; } else if(newstr.startsWith("//")||newstr.length()==0){ num+=0 ; }else if(!flag){ num+=1 ; } } } catch (Exception e) { e.printStackTrace(); } }else { System.out.println("不是文件!"); } System.out.println(f+"文件的代码行数是:"+num); return num; } }