[Java]
Package com. util;
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 {
Static long commentLine = 0;
Static long whiteLine = 0;
Static long normalLine = 0;
Static long totalLine = 0;
Static boolean comment = false;
Public static void main (String [] args ){
File file = new File ("D: \ MyEclipse \ Workspaces \ Util \ src \ com \ util \ Table. java "); // enter the path of the folder where statistics are needed.
GetChild (file );
System. out. println ("valid code lines:" + normalLine );
System. out. println ("comment row:" + commentLine );
System. out. println ("Number of blank rows:" + whiteLine );
System. out. println ("total code lines:" + totalLine );
}
Private static void getChild (File child) {// traverses sub-Directories
If (child. getName (). matches (". * \. java $") {// only query java files
BufferedReader br = null;
Try {
Br = new BufferedReader (new FileReader (child ));
} Catch (FileNotFoundException e1 ){
E1.printStackTrace ();
}
String line = "";
Try {
While (line = br. readLine ())! = Null ){
Parse (line );
}
} Catch (IOException e ){
E. printStackTrace ();
}
}
If (child. listFiles ()! = Null ){
For (File f: child. listFiles ()){
GetChild (f );
}
}
}
Private static void parse (String line ){
Line = line. trim ();
TotalLine ++;
If (line. length () = 0 ){
WhiteLine ++;
} Else if (comment ){
CommentLine ++;
If (line. endsWith ("*/")){
Comment = false;
} Else if (line. matches (". * \ */. + ")){
NormalLine ++;
Comment = false;
}
} Else if (line. startsWith ("//")){
CommentLine ++;
} Else if (line. matches (". + //.*")){
CommentLine ++;
NormalLine ++;
} Else if (line. startsWith ("/*") & line. matches (". + \ */. + ")){
CommentLine ++;
NormalLine ++;
If (findPair (line )){
Comment = false;
} Else {
Comment = true;
}
} Else if (line. startsWith ("/*")&&! Line. endsWith ("*/")){
CommentLine ++;
Comment = true;
} Else if (line. startsWith ("/*") & line. endsWith ("*/")){
CommentLine ++;
Comment = false;
} Else if (line. matches (". + /\\*.*")&&! Line. endsWith ("*/")){
CommentLine ++;
NormalLine ++;
If (findPair (line )){
Comment = false;
} Else {
Comment = true;
}
} Else if (line. matches (". +/\ *. *") & line. endsWith ("*/")){
CommentLine ++;
NormalLine ++;
Comment = false;
} Else {
NormalLine ++;
}
}
Private static boolean findPair (String line) {// you can check whether a pair of/* and */appear in a row.
Int count1 = 0; www.2cto.com
Int count2 = 0;
Pattern p = Pattern. compile ("/\\*");
Matcher m = p. matcher (line );
While (m. find ()){
Count1 ++;
}
P = Pattern. compile ("\\*/");
M = p. matcher (line );
While (m. find ()){
Count2 ++;
}
Return (count1 = count2 );
}
}
Author: ll136078