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 public class CodeCounter { 8 9 static long normalLines = 0; 10 static long commentLines = 0; 11 static long whiteLines = 0; 12 13 public static void main(String[] args) { 14 File f = new File("D:\\share\\JavaProjects\\TankWar1.9.11\\src"); 15 File[] codeFiles = f.listFiles(); 16 for(File child : codeFiles){ 17 if(child.getName().matches(".*\\.java$")) { 18 parse(child); 19 } 20 } 21 22 System.out.println("normalLines:" + normalLines); 23 System.out.println("commentLines:" + commentLines); 24 System.out.println("whiteLines:" + whiteLines); 25 26 } 27 28 private static void parse(File f) { 29 BufferedReader br = null; 30 boolean comment = false; 31 try { 32 br = new BufferedReader(new FileReader(f)); 33 String line = ""; 34 while((line = br.readLine()) != null) { 35 line = line.trim(); 36 if(line.matches("^[\\s&&[^\\n]]*$")) { 37 whiteLines ++; 38 } else if (line.startsWith("/*") && !line.endsWith("*/")) { 39 commentLines ++; 40 comment = true; 41 } else if (line.startsWith("/*") && line.endsWith("*/")) { 42 commentLines ++; 43 } else if (true == comment) { 44 commentLines ++; 45 if(line.endsWith("*/")) { 46 comment = false; 47 } 48 } else if (line.startsWith("//")) { 49 commentLines ++; 50 } else { 51 normalLines ++; 52 } 53 } 54 } catch (FileNotFoundException e) { 55 e.printStackTrace(); 56 } catch (IOException e) { 57 e.printStackTrace(); 58 } finally { 59 if(br != null) { 60 try { 61 br.close(); 62 br = null; 63 } catch (IOException e) { 64 e.printStackTrace(); 65 } 66 } 67 } 68 } 69 70 }
原文地址:https://www.cnblogs.com/XiDaPuBen/p/8678754.html
时间: 2024-10-18 15:25:29