Java was originally designed to collect statistics on the number of Java code lines written in its own code lines. The function is very simple. It provides a file path and counts the total number of lines of code, comment lines, empty lines, and so on.
Implementation: Typical recursion is used to traverse all java files: Determine whether the file is a directory or a file. If it is a directory, it traverses all the sub-files of the file, call this method recursively for all sub-files. For java files, count the number of rows directly and use a regular expression to count the number of rows. The core code is as follows:
Traverse all java files:
Public void getfilename (string filepath)
{
File F = new file (filepath );
If (! F. isdirectory () // not a directory
{
If (F. getname (). endswith (". Java "))
{
Count (f );
}
}
Else // is the Directory
{
String [] filelist = f. List ();
For (INT I = 0; I <filelist. length; I ++)
{
File file = new file (filepath + "//" + filelist [I]);
If (! File. isdirectory () // not a directory
{
If (file. getname (). endswith (". Java "))
{
Count (File );
}
}
Else // is the Directory
{
Getfilename (file. getpath (); // Note: it is not getname ()!
}
}
}
}
Count the number of lines of code:
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 ++;
}
}
Complete code and runnable jar files are available inHttp://download.csdn.net/user/china8848.