Java Regular Expression (3), Code volume statistical tool (count the number of comments, codes, and blank lines in the java source file)

Source: Internet
Author: User

Idea: because the content of each java source file consists of java statements, blank lines, and annotations (excluding annotations), when calculating the content of each of the three parts of a file, you only need to write three regular expressions that match the content. Then, read each row in the file through the IO stream, and accumulate the number of Matching Parts Based on the regular expression matching results.
Comment lines: single line comment (//), multi-line comment, and document comment. Regular: (//) | (/\ * +) | (^ \ s) * \ *) | (^ \ s) * \ * +/) +
Blank line: Only spaces, \ t, \ n, and other non-visual characters in a row represent blank lines. Regular: ^ \ s * $
Line of code: Use a semicolon (;) to end with a valid line of code. Regular :(?! Import | package). +; \ s * (//) | (/\ * + )).*)*
Implementation Method:
1. Enter the java file path or directory to be counted on the console.
2. Create a File object based on the path, determine whether the File is valid, and give a prompt. Finally, bind the file to the IO stream
3. Read a row in the file cyclically, and record the number of Matching Parts Based on the regular expression matching results.

The complete code is as follows:
[Java]
Package regex;
 
Import java. io. BufferedReader;
Import java. io. File;
Import java. io. FileFilter;
Import java. io. FileInputStream;
Import java. io. FileNotFoundException;
Import java. io. IOException;
Import java. io. InputStreamReader;
Import java. util. collections;
Import java. util. regex. Pattern;
 
/**
* Code statistics Tool
* Count the number of lines of comments, blank lines, and code lines in a java source file or all java source files in a directory
* Note: includes single-line comments (//), multi-line comments, and document comments.
* Blank row: blank rows are displayed if no content exists in a row.
* Code line: A statement ending with a semicolon (;). Valid code lines can be counted.
*/
Public class CodeStatDemo {

// Record the number of comment rows
Static long annotationLine = 0;

// Record the number of blank rows
Static long blankLine = 0;

// Record the number of valid code lines
Static long codeLine = 0;

// Total number of lines of code
Static long totalLine = 0;

// Total number of files
Static long fileCount = 0;
 
Public static void main (String [] args) throws FileNotFoundException {
System. out. println ("Enter the java file or java directory for counting the code volume :");
Running in = new Processing (System. in );
String filePath = in. nextLine ();

File file = new File (filePath );
// Statistics on the amount of code executed based on the file name and directory entered by the user
CodeStat (file );

System. out. println ("---------- statistical result ---------");
System. out. println ("number of files:" + fileCount + ");
System. out. println (file + "Total number of file/directory rows:" + totalLine );
System. out. println ("number of lines of code:" + codeLine );
System. out. println ("comment row:" + annotationLine );
System. out. println ("Number of blank rows:" + blankLine );
Long otherLine = totalLine-(codeLine + annotationLine + blankLine );
System. out. println ("other rows:" + otherLine );

}
 
Private static void codeStat (File file) throws FileNotFoundException {
If (file = null |! File. exists ())
Throw new FileNotFoundException (file + ", the file does not exist! ");

FileCount ++; // the total number of files

If (file. isDirectory ()){
File [] files = file. listFiles (new FileFilter (){

@ Override
Public boolean accept (File pathname ){
Return pathname. getName (). endsWith (". java") | pathname. isDirectory ();
}
});

For (File target: files ){
CodeStat (target );
}
} Else {
BufferedReader bufr = null;
Try {
// Bind the file in the specified path to the upload stream
Bufr = new BufferedReader (new InputStreamReader (new FileInputStream (file )));
} Catch (FileNotFoundException e ){
Throw new RuntimeException (file + ", the file does not exist! "+ E );
}

// Define the regular match matching each row
Pattern annotationLinePattern = Pattern. compile ("(//) | (/\ * +) | (^ \ s) * \ *) | (^ \ s) * \ * +/) + ",
Pattern. MULTILINE + Pattern. DOTALL); // comment on a vertex (matching a single line, multiple lines, and document comments)

Pattern blankLinePattern = Pattern. compile ("^ \ s * $"); // blank line (match the carriage return, tab key, and space)

Pattern codeLinePattern = Pattern. compile ("(?! Import | package). +; \ s * (//) | (/\ * + )).*)*",
Pattern. MULTILINE + Pattern. DOTALL); // code line (end with a semicolon as a valid statement, but does not include the import and package statements)

// Traverse each row in the file and record the matching results of each row based on the regular matching results
String line = null;
Try {
While (line = bufr. readLine ())! = Null ){
If (annotationLinePattern. matcher (line). find ()){
AnnotationLine ++;
}

If (blankLinePattern. matcher (line). find ()){
BlankLine ++;
}

If (codeLinePattern. matcher (line). matches ()){
CodeLine ++;
}

TotalLine ++;
}

} Catch (IOException e ){
Throw new RuntimeException ("An error occurred while reading the file! "+ E );
} Finally {
Try {
Bufr. close (); // close the file input stream and Release System Resources
} Catch (IOException e ){
Throw new RuntimeException ("An error occurred while closing the file input stream! ");
}
}
}
}
}
Test results:

Author: xyang81

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.