Java计算代码行数
2017-08-04 16:12
295 查看
看到一个计算代码行数的机试题目,demo如下:
package demo; import java.io.*; /** * 统计代码行数demo * author:lizhi */ public class StatisticCodeLines { public static int normalLines = 0; //有效程序行数 public static int whiteLines = 0; //空白行数 public static int commentLines = 0; //注释行数 public static void main(String[] args) throws IOException { File file = new File("D:\\workplace\\lzwebparent\\src\\main\\demo"); if (file.exists()) { statistic(file); } System.out.println("总有效代码行数: " + normalLines); System.out.println("总空白行数:" + whiteLines); System.out.println("总注释行数:" + commentLines); System.out.println("总行数:" + (normalLines + whiteLines + commentLines)); } private static void statistic(File file) throws IOException { if (file.isDirectory()) { File[] files = file.listFiles(); for (int i = 0; i < files.length; i++) { statistic(files[i]); } } if (file.isFile()) { //统计扩展名为java的文件 if (file.getName().matches(".*\\.java")) { parse(file); } } } public static void parse(File file) { BufferedReader br = null; // 判断此行是否为注释行 boolean comment = false; int temp_whiteLines = 0;//空白行数 int temp_commentLines = 0;//注释行数 int temp_normalLines = 0; //有效程序行数 try { br = new BufferedReader(new FileReader(file)); String line = ""; while ((line = br.readLine()) != null) { line = line.trim(); if (line.matches("^[\\s&&[^\\n]]*$")) { // 空行 whiteLines++; temp_whiteLines++; }else if (line.startsWith("/*") && line.endsWith("*/")) { // 判断此行为"/*xxx*/"的注释行 commentLines++; temp_commentLines++; } else if (line.startsWith("/*") && !line.endsWith("*/")) { // 判断此行为"/*"开头的注释行 commentLines++; temp_commentLines++; comment = true; } else if (comment == true && !line.endsWith("*/")) { // 为多行注释中的一行(不是开头和结尾) commentLines++; temp_commentLines++; } else if (comment == true && line.endsWith("*/")) { // 为多行注释的结束行 commentLines++; temp_commentLines++; comment = false; } else if (line.startsWith("//")) { // 单行注释行 commentLines++; temp_commentLines++; } else { // 正常代码行 normalLines++; temp_normalLines++; } } System.out.println("有效行数" + temp_normalLines + " ,空白行数" + temp_whiteLines + " ,注释行数" + temp_commentLines + " ,总行数" + (temp_normalLines + temp_whiteLines + temp_commentLines) + " " + file.getName()); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } finally { if (br != null) { try { br.close(); br = null; } catch (IOException e) { e.printStackTrace(); } } } } }
相关文章推荐
- JAVA作业——输入指定文件,计算代码行数
- JAVA作业—从命令行输入两个参数打开文件并计算代码行数
- JAVA作业—从命令行输入两个参数打开文件并计算代码行数 .
- [Java] 正则表达式 02 EmailSpider 抓邮件, CodeCounter 统计程序有效代码行数
- 输出该目录下指定类型文件(.cs, .java)的个数、文件的总行数、空行数、注释行数、代码行数
- 计算三角形周长和面积java代码
- java实现计算两个整数的最大公约数代码及附图
- [原创]Python小工具 —— 计算 文件 或 文件夹及其所有子文件夹中所有文件 的 代码行数
- Java基础计算三角形面积的代码
- 计算编写代码行数
- Python计算一个项目中含有的代码行数
- 代码行数统计的Java和Python实现
- 统计java代码文件的代码行数(空行、注释不能计数)
- 黑马程序员 用OC实现的一个计算文件夹下代码行数的小程序
- java 实现字符串以及文件的md5、sha计算完整代码
- java文件代码行数统计
- 相似度计算方式的总结:java或python实现代码
- java计算集合对称差的示例代码
- 黑马程序员——OCFoundation框架-9:计算某个文件夹下的代码行数