當初初學java是為了統計自己的程式碼數寫的java程式碼數統計工具,功能很簡單,給出一個檔案路徑,統計出代碼的總行數,注釋行數,空行行數等等。
實現方面:遍曆所有的java檔案時用到了典型的遞迴:判斷給是檔案是目錄還是檔案,如果是目錄,就遍曆檔案所有的子檔案,對所有子檔案遞迴調用該方法,如果是java檔案,直接統計行數,統計行數用到了Regex。核心的代碼如下:
遍曆所有java檔案:
public void getFileName(String filePath)
{
File f = new File(filePath);
if(!f.isDirectory())//不是目錄
{
if(f.getName().endsWith(".java"))
{
count(f);
}
}
else//是目錄
{
String []fileList = f.list();
for(int i=0;i<fileList.length;i++)
{
File file = new File(filePath+"//"+fileList[i]);
if(!file.isDirectory())//不是目錄
{
if(file.getName().endsWith(".java"))
{
count(file);
}
}
else //是目錄
{
getFileName(file.getPath());//注意:不是getname()!
}
}
}
}
統計程式碼數:
while((line = br.readLine())!=null)
{
line = line.trim();
if(line.matches("^[[//s]&&[^//n]]*$")) // spaceLine ?*$
{
spaceLine++;
}
else if(line.startsWith("//")||(line.startsWith("/*")&&line.endsWith("*/")))
{
commentLine++;
}
else if(line.startsWith("/*")&&!line.endsWith("*/"))
{
commentLine++;
comment = true;
}
else if((line.endsWith("*/"))&&comment==true)
{
commentLine++;
comment = false;
}
else if(comment==true)
{
commentLine++;
}
else
{
normalLine++;
}
}
完整的代碼和可啟動並執行jar在http://download.csdn.net/user/china8848可以獲得。