统计文件夹下java代码行数

编写这个程序主要就是判断是否是文件夹,和是否是java文件。编程时注意成员变量和局部变量的使用,我一开始使用局部变量来递归,不过取到的值都是0,因为在递归中重新赋值了。名字取的时候没注意。。。

CountList2.java//用来统计java代码行数

import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;

public class CountList2 {
int countSum;//代码行数

public int getFile(String filePath) throws FileNotFoundException {
  try {
   File file = new File(filePath);
   if (file.isDirectory()) {//判断是否是文件夹
    File[] codeFiles = file.listFiles();
    int s = codeFiles.length;
    for (int i = 0; i < s; i++) {
     getFile(codeFiles[i].getPath());
    }
   } else {
    if (file.getName().endsWith(".java")) {//判断是否是java文件
     System.out.println(file.getName());//输出java文件名称
     countSum += fileList(file);
    }
   }
  } catch (FileNotFoundException e4) {
   System.out.println("erroe1");
   e4.printStackTrace();
  } catch (@SuppressWarnings("hiding") IOException e1) {
   System.out.println("erroe2");
   e1.printStackTrace();
  }
  return countSum;
}

public int fileList(File file) {
  int countSum = 0;//代码行数
  int blankSum = 0;//空白行数
  int commentSum = 0;//注释行数
  BufferedReader br = null;
  try {
   br = new BufferedReader(new FileReader(file));
   String line = null;
   while ((line = br.readLine()) != null) {
    line = line.trim();
    if (line.matches("^[\\s&&[^\\n]]*$")) {
     blankSum++;
    } else if (line.startsWith("//")) {
     commentSum++;
    } else if (line.startsWith("/*")) {
     commentSum++;
    } else if (line.startsWith("*")) {
     commentSum++;
    } else if (line.endsWith("*/")) {
     commentSum++;
    } else {
     countSum++;
    }
   }
   br.close();
  } catch (Exception e) {
   System.out.println("erroe3");
   e.printStackTrace();
  }
  return countSum;
}

}

countList1.java//用来测试

import java.io.FileNotFoundException;

public class countList1 {

public static void main(String[] args) throws FileNotFoundException {
  String filePath = "E:\\nbtserver";
  CountList2 fn = new CountList2();
  int countSum1=fn.getFile(filePath);
  System.out.println("countSum: " + countSum1);
}
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值