package com.lbwleon.io;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.io.LineNumberReader;
import java.util.ArrayDeque;
import java.util.ArrayList;
import java.util.Deque;
public class Count {
/**
*
* @param f
* @return
*/
public static int count(File f) {
if (f == null) {
return -1;
}
ArrayList<File> al = new ArrayList<File>();
al = get(f);
int sum = 0;
LineNumberReader lnr = null;
for (int i = 0; i < al.size(); i++) {
try {
lnr = new LineNumberReader(new FileReader(al.get(i)));
String s = null;
while ((s = lnr.readLine()) != null) {
/* 注释块的判断 */
if (s.trim().startsWith("/*") || s.trim().startsWith("/**")
&& !s.trim().endsWith("*/")) {
while (!s.trim().endsWith("*/")) {
s = s + lnr.readLine();
}
}
if (isEffective(s)) {
System.out.println(s);
sum++;
}
}
// System.out.print(lnr.readLine());
// System.out.println(lnr.getLineNumber());
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
// System.out.println(sum);
return sum;
}
/**
* 判断是否为有效代码
*
* @param s
* @return
*/
public static boolean isEffective(String s) {
if (s.trim().length() == 0) {
return false; // 判断是否为空行
} else if (s.trim().startsWith("/*") && s.trim().endsWith("*/")) {
return false; // 判断 "/* */" 形式的注释
} else if (s.trim().startsWith("//")) {
return false; // 判断 "//" 形式的注释
} else if (s.trim().startsWith("/**") && s.trim().endsWith("*/")) {
return false;
}
return true;
}
/**
* 获得目录中的Java文件 并传入al的ArrayList集合中
*
* @param f
* 要获取Java文件的目录
* @return 存放java文件的集合
*/
public static ArrayList<File> get(File f) {
Deque<File> ad = new ArrayDeque<File>();
ArrayList<File> al = new ArrayList<File>();
if (f.isFile()) {
if (f.getName().endsWith(".java")) {
al.add(f);
return al;
}
return null;
} else if (f.isDirectory()) {
ad.offer(f);
File[] fs = null;
while (ad.peek() != null) {
fs = ad.poll().listFiles(new JavaFileFilter());
for (File temp : fs) {
if (temp.isFile()) {
al.add(temp);
} else {
ad.offer(temp);
}
}
}
}
return al;
}
public static void main(String[] args) {
System.out.println(count(new File("d:/java")));
}
}