部分代码来至于 http://www.oschina.net/code/snippet_615783_21235
添加一个 循环获取文件的方法
public class test {
static long normalLine=0;
static long commentLine=0;
static long whiteLine=0;
static List<File> files = new ArrayList<>();
public static void p(Object obj){
System.out.println(obj);
}
public static void countcode(File f){
BufferedReader br=null;
boolean bln=false;
try{
br=new BufferedReader(new FileReader(f));
String line="";
try {
while((line = br.readLine()) != null) {
line=line.trim();
if(line.matches("^[\\s&&[^\\n]]*$")){
whiteLine+=1;
}else if(line.startsWith("/*")&&!line.equals("*/")){
commentLine+=1;
bln=true;
}else if (bln==true){
commentLine+=1;
if(line.endsWith("*/")){
bln=false;
}
}else if(line.startsWith("/*")&&line.endsWith("*/")){
commentLine+=1;
}else if(line.startsWith("//")){
commentLine+=1;
}else {
normalLine+=1;
}
}
}
catch (IOException e) {
e.printStackTrace();
}
}catch(FileNotFoundException e){
e.printStackTrace();
}finally {
if(br!=null){
try {
br.close();
br=null;
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
public static void main(String args[]){
//读取该目录下面的 所有 .java 文件进行统计。目前没进行文件夹递归访问
File f=new File("E:\\能信\\project\\TY-P-JK-2016-047_能投微信平台\\04_成果物\\01_代码\\www");
listMyFiles(f);
for (File eachfile:files){
System.out.println(eachfile);
String name = eachfile.getName();
if(name.matches(".*\\.java$") || name.matches(".*\\.html$")
|| name.matches(".*\\.js$") || name.matches(".*\\.css$") || name.matches(".*\\.jsp$")){
countcode(eachfile);
}
}
p("注释的代码行数:"+commentLine);
p("空白的代码行数:"+whiteLine);
p("有效的代码行数:"+normalLine);
}
public static void listMyFiles(File file) {
File[] fs = file.listFiles();
if (file.isDirectory()) {
for (File file2 : fs) {
listMyFiles(file2);
}
}else{
files.add(file);
}
}
}