部分代碼來至於 http://www.oschina.net/code/snippet_615783_21235css
添加一個 循環獲取文件的方法html
public class test { static long normalLine=0; static long commentLine=0; static long whiteLine=0; static List<File> files = new ArrayList<>(); public static void p(Object obj){ System.out.println(obj); } public static void countcode(File f){ BufferedReader br=null; boolean bln=false; try{ br=new BufferedReader(new FileReader(f)); String line=""; try { while((line = br.readLine()) != null) { line=line.trim(); if(line.matches("^[\\s&&[^\\n]]*$")){ whiteLine+=1; }else if(line.startsWith("/*")&&!line.equals("*/")){ commentLine+=1; bln=true; }else if (bln==true){ commentLine+=1; if(line.endsWith("*/")){ bln=false; } }else if(line.startsWith("/*")&&line.endsWith("*/")){ commentLine+=1; }else if(line.startsWith("//")){ commentLine+=1; }else { normalLine+=1; } } } catch (IOException e) { e.printStackTrace(); } }catch(FileNotFoundException e){ e.printStackTrace(); }finally { if(br!=null){ try { br.close(); br=null; } catch (IOException e) { e.printStackTrace(); } } } } public static void main(String args[]){ //讀取該目錄下面的 全部 .java 文件進行統計。目前沒進行文件夾遞歸訪問 File f=new File("E:\\能信\\project\\TY-P-JK-2016-047_能投微信平臺\\04_成果物\\01_代碼\\www"); listMyFiles(f); for (File eachfile:files){ System.out.println(eachfile); String name = eachfile.getName(); if(name.matches(".*\\.java$") || name.matches(".*\\.html$") || name.matches(".*\\.js$") || name.matches(".*\\.css$") || name.matches(".*\\.jsp$")){ countcode(eachfile); } } p("註釋的代碼行數:"+commentLine); p("空白的代碼行數:"+whiteLine); p("有效的代碼行數:"+normalLine); } public static void listMyFiles(File file) { File[] fs = file.listFiles(); if (file.isDirectory()) { for (File file2 : fs) { listMyFiles(file2); } }else{ files.add(file); } } }