1 import java.io.BufferedReader; 2 import java.io.File; 3 import java.io.FileNotFoundException; 4 import java.io.FileReader; 5 import java.io.IOException; 6 7 8 9 public class CodeCounter { 10 11 static int normalLines = 0;//普通行 12 static int commentLines = 0;//注释行 13 static int blankLines = 0;//空行 14 15 16 public static void main(String[] args) { 17 18 File f = new File("D:/code"); 19 File[] codeFile = f.listFiles(); 20 for(File child :codeFile){ 21 22 if(child.getName().matches(".*\\.java$"));{ 23 parse(child); 24 } 25 } 26 27 28 29 System.out.println("normalLines = " + normalLines); 30 System.out.println("commentLines = " + commentLines); 31 System.out.println("blankLines = " + blankLines); 32 } 33 34 35 private static void parse(File f) { 36 BufferedReader br = null; 37 boolean comment = false; 38 try { 39 br = new BufferedReader(new FileReader(f)); 40 String line = ""; 41 while((line = br.readLine())!=null){ 42 line = line.trim(); 43 if(line.matches("^[\\s&&[^\\n]]*")){ 44 blankLines++; 45 }else if(line.matches("/*")&&!line.endsWith("*/")){ 46 commentLines++; 47 comment = true; 48 49 }else if( true == comment){ 50 commentLines++; 51 if(line.endsWith("*/")){ 52 comment = false; 53 } 54 }else{ 55 normalLines++; 56 } 57 58 } 59 60 } catch (FileNotFoundException e) { 61 // TODO Auto-generated catch block 62 e.printStackTrace(); 63 } catch (IOException e) { 64 // TODO Auto-generated catch block 65 e.printStackTrace(); 66 }finally{ 67 if(br!=null){ 68 try { 69 br.close(); 70 br= null; 71 } catch (IOException e) { 72 // TODO Auto-generated catch block 73 e.printStackTrace(); 74 } 75 } 76 77 } 78 79 } 80 81 }