日期:2014-05-20 浏览次数:20808 次
import java.io.BufferedReader; import java.io.File; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.IOException; import java.util.regex.Matcher; import java.util.regex.Pattern; public class CodeCounter { static int blankLine; //空白行 static int commentLine; //注释行 static int validLine; //有效行 static Pattern pBlank = Pattern.compile("^[\\s[^\\n]]*$"); public static void main(String[] args) { File f =new File("E:\\Eclipse\\Workspace\\RegExp\\src\\"); File[] fa = f.listFiles(); BufferedReader br = null;; String line = null; for(File child : fa) { if(child.getName().matches(".*\\.java$")) { try { br = new BufferedReader(new FileReader(child)); while((line=br.readLine())!=null) { parse(line); br.close(); } } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } } System.out.println("blankLine: " + blankLine); System.out.println("commentLine: " + commentLine); System.out.println("validLine: " + validLine); } private static void parse(String line) { boolean flag = false; if(line.matches(pBlank.pattern())) { blankLine++; }else if(line.startsWith("/*")&&!line.endsWith("*/")) { commentLine++; flag = true; }else if(flag==true) { commentLine++; if(line.endsWith("*/")) flag = false; }else validLine++; } }