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

For example, to count the workload of a Java programmer writing code in one day (for example, the number of lines of valid code, the number of blank lines, and the number of lines of comments), this tool may serve as a reference.

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 row:Single line comment (//), multi-line comment, and document comment. Regular Expression:(//) | (/\ * +) | (^ \ S) * \ *) | (^ \ s) * \ * +/) +

Blank line:Only spaces, \ t, \ n, and other non-visual characters in a row represent blank lines. Regular Expression:^ \ S * $

Code line:End with a semicolon ";" as a valid line of code. Regular Expression:(?! 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:
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. imports; import Java. util. regEx. pattern;/***** code statistics Tool * counts comments, blank lines, and lines of code lines in a Java source file or all Java source files in a directory * comments: including single-line comments (//), multi-line comments, and document comments * blank lines: blank lines with no content in a line * code lines: Semicolon "; "End of a statement, you can Take statistics as a valid line of code */public class codestatdemo {// record the number of comment lines static long annotationline = 0; // record the number of blank lines static long blankline = 0; // record the number of valid code lines static long codeline = 0; // The total number of code lines static long totalline = 0; // the 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 code statistics:"); Statistics in = new statistics (system. in); string filepath = in. nextline (); File = new file (filepath); // 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 + Bla Nkline); 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 ++; // Add the number of files if (file. isdirectory () {file [] files = file. listfiles (New filefilter () {@ overridepublic 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);} Cat CH (filenotfoundexception e) {Throw new filenotfoundexception (File + ", the file does not exist! "+ E);} // defines the regular pattern annotationlinepattern = pattern that matches each row. compile ("(//) | (/\ * +) | (^ \ s) * \ *) | (^ \ s) * \ * +/) + ", pattern. multiline + pattern. dotall); // annotation (matching a single line, multiple lines, and document comments) pattern blanklinepattern = pattern. compile ("^ \ s * $"); // a blank line (matching the carriage return, Tab key, and space) pattern codelinepattern = pattern. compile ("(?! Import | package ). +; \ s * (//) | (/\ * + )). *) * ", pattern. multiline + pattern. dotall); // code line check (end with a semicolon as a valid statement, but does not include the import and package statements) // traverse each row in the file, record the matching result of each row according to the regular expression matching result 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:

Related Article

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.