This applet can effectively count the number of lines of valid code, comments, and blank lines in a project folder (including sub-Directories) of the. java file,
Try it.
Package com. zhanglei. Java;
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 {
/**
* @ Param args
*/
Public static void main (String [] args ){
// TODO Auto-generated method stub
Counter c = new Counter ("D :\\ Android_space \ test \ src \"); // modify the directory here
C. countJavaFile (c. projectPath );
}
}
Class Counter {
String projectPath;
Long blankLineNum = 0l;
Long zhushiLineNum = 0l;
Long codeLineNum = 0l;
Public Counter (String projectPath ){
Super ();
This. projectPath = projectPath;
}
Public void countJavaFile (String path ){
File f = new File (path );
If (f. isDirectory ()){
File [] childFiles = f. listFiles ();
For (int I = 0; I <childFiles. length; I ++ ){
CountJavaFile (childFiles [I]. getAbsolutePath ());
}
} Else {
If (f. getName (). matches (". * \. java $") {// determine whether the file is a. java File
// BlankLineNum = 0l;
// ZhushiLineNum = 0l;
// CodeLineNum = 0l;
Parse (f );
}
}
}
Public void parse (File f ){
BufferedReader br = null;
Try {
Br = new BufferedReader (new FileReader (f ));
String line = "";
Pattern blankP = Pattern. compile ("^ [\ s & [^ \ n] *");
Matcher blankM;
Boolean comment = false;
While (line = br. readLine ())! = Null ){
Line = line. trim ();
Balancer = balancer. matcher (line );
If (blankM. matches ()){
BlankLineNum ++;
} Else if (line. startsWith ("/*")&&! (Line. endsWith ("*/"))){
Comment = true;
ZhushiLineNum ++;
} Else if (line. startsWith ("/*") & line. endsWith ("*/")){
ZhushiLineNum ++;
} Else if (true = comment ){
ZhushiLineNum ++;
If (line. startsWith ("*/")){
Comment = false;
}
} Else if (line. startsWith ("//")){
ZhushiLineNum ++;
}
Else {
CodeLineNum ++;
}
} Www.2cto.com
System. out. println ("file" + f. getAbsolutePath () + ": the total number of empty rows:" + blankLineNum + ", the total number of commented rows :"
+ ZhushiLineNum + ", accumulative code lines:" + codeLineNum );
} Catch (FileNotFoundException e ){
// TODO Auto-generated catch block
E. printStackTrace ();
} Catch (IOException e ){
// TODO Auto-generated catch block
E. printStackTrace ();
} Finally {
If (br! = Null ){
Try {
Br. close ();
} Catch (IOException e ){
// TODO Auto-generated catch block
E. printStackTrace ();
}
}
}
}
}