package test; import java.io.BufferedReader; import java.io.File; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.IOException; /** * 2009-07-13 代码统计程序 * * @author heyuanbo * */ public class CodeCounter { private static long normalLines = 0; // 正常行数 private static long commentLines = 0; // 注释行数 private static long whiteLines = 0; // 空白行数 public static void main(String[] args) { File file = new File("E://heyuanbo//CodeCounter//src//test//"); File[] files = file.listFiles(); for (File f : files) { if (f.getName().matches(".*//.java$")) { parse(f); // System.out.println(f.getName()); } // System.out.println("f.getName(): " + f.getName()); } System.out.println("normalLines: " + normalLines); System.out.println("commentLines: " + commentLines); System.out.println("whiteLines: " + whiteLines); } private static void parse(File f) { BufferedReader br = null; boolean hasComment = false; String line = ""; try { br = new BufferedReader(new FileReader(f)); } catch (FileNotFoundException e) { e.printStackTrace(); } try { while ((line = br.readLine()) != null) { // while (br.read() != -1) { // line = line.trim(); // line = br.readLine(); line = line.trim(); System.out.println(line); if (line.matches("^[//s&&[^//n]]*$")) { whiteLines++; } else if (line.startsWith("/*") && !line.endsWith("*/")) { // /*多行注释*/ commentLines++; hasComment = true; } else if (line.startsWith("/*") && line.endsWith("*/")) { // /*单行注释*/ commentLines++; } else if (hasComment == true) { commentLines++; if (line.endsWith("*/")) { hasComment = false; } } else if (line.startsWith("//")) { commentLines++; } else { normalLines++; } } } catch (IOException e) { e.printStackTrace(); } finally { if (br != null) { try { br.close(); } catch (IOException e) { e.printStackTrace(); } br = null; } } } }