import java.io.BufferedReader;<br />import java.io.File;<br />import java.io.FileNotFoundException;<br />import java.io.FileReader;<br />import java.io.IOException;</p><p>/**<br /> * 程式碼數統計<br /> * @author 霧非霧<br /> * @date 2011-05-25<br /> */<br />public class StatisticCodeLines {</p><p>public static int normalLines = 0; //有效程式行數<br />public static int whiteLines = 0; //空白行數<br />public static int commentLines = 0; //注釋行數</p><p>public static void main(String[] args) throws IOException{</p><p>File file = new File("d://workspace//project");<br />if (file.exists()) {<br />statistic(file);<br />}<br />System.out.println("總有效程式碼數: " + normalLines);<br />System.out.println("總空白行數:" + whiteLines);<br />System.out.println("總注釋行數:" + commentLines);<br />System.out.println("總行數:" + (normalLines + whiteLines + commentLines));<br />}</p><p>private static void statistic(File file) throws IOException {</p><p>if (file.isDirectory()) {<br />File[] files = file.listFiles();<br />for (int i = 0; i < files.length; i++) {<br />statistic(files[i]);<br />}<br />}<br />if (file.isFile()) {<br />//統計副檔名為java的檔案<br />if(file.getName().matches(".*//.java")){<br />parse(file);<br />}<br />}</p><p>}</p><p>public static void parse(File file) {<br />BufferedReader br = null;<br />// 判斷此行是否為注釋行<br />boolean comment = false;<br />int temp_whiteLines = 0;<br />int temp_commentLines = 0;<br />int temp_normalLines = 0;</p><p>try {<br />br = new BufferedReader(new FileReader(file));<br />String line = "";<br />while ((line = br.readLine()) != null) {<br />line = line.trim();<br />if (line.matches("^[//s&&[^//n]]*$")) {<br />// 空行<br />whiteLines++;<br />temp_whiteLines++;<br />} else if (line.startsWith("/*") && !line.endsWith("*/")) {<br />// 判斷此行為"/*"開頭的注釋行<br />commentLines++;<br />comment = true;<br />} else if (comment == true && !line.endsWith("*/")) {<br />// 為多行注釋中的一行(不是開頭和結尾)<br />commentLines++;<br />temp_commentLines++;<br />} else if (comment == true && line.endsWith("*/")) {<br />// 為多行注釋的結束行<br />commentLines++;<br />temp_commentLines++;<br />comment = false;<br />} else if (line.startsWith("//")) {<br />// 單行注釋行<br />commentLines++;<br />temp_commentLines++;<br />} else {<br />// 正常程式碼<br />normalLines++;<br />temp_normalLines++;<br />}<br />}</p><p>System.out.println("有效行數" + temp_normalLines +<br /> " ,空白行數" + temp_whiteLines +<br /> " ,注釋行數" + temp_commentLines +<br /> " ,總行數" + (temp_normalLines + temp_whiteLines + temp_commentLines) +<br /> " " + file.getName());</p><p>} catch (FileNotFoundException e) {<br />e.printStackTrace();<br />} catch (IOException e) {<br />e.printStackTrace();<br />} finally {<br />if (br != null) {<br />try {<br />br.close();<br />br = null;<br />} catch (IOException e) {<br />e.printStackTrace();<br />}<br />}<br />}<br />}</p><p>}