1.根据指定项目目录下中,统计被import最多的类。
package org.sh.countimport;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
/**
* 根据指定项目目录下(可以认为是java源文件目录)中,统计被import最多的类。
*
* @author Administrator
*
*/
public class MostImportFile {
private Map<String, Integer> map = new HashMap<String, Integer>();
public static void main(String[] args) {
MostImportFile mf = new MostImportFile();
String path = "D://workspaces//chinatravel//src//org//chi";
mf.GetFile(path);
String result= mf.getMostImportFile();
System.out.println("******:"+result);
}
private void GetFile(String filePath) {
File file = new File(filePath);
DepthSearch(file);
}
public String DepthSearch(File f) {
if (f.isDirectory()) {
File[] files = f.listFiles();
if (files != null) {
for (File file : files) {
DepthSearch(file);
}
}
} else {// 是文件
try {
findNumberofImport(f);
} catch (Exception e) {
e.printStackTrace();
}
}
return null;
}
private void findNumberofImport(File f) throws Exception {
InputStream in = new FileInputStream(f);
BufferedReader reader = new BufferedReader(new InputStreamReader(in));
String str = "";
while ((str = reader.readLine()) != null) {
if(str.startsWith("package")||"".equals(str)){
continue;
}
if (str.startsWith("import")) {
str = str.replaceAll("\\s*", "");
str = str.substring(6);
Integer value = map.get(str);
if(value==null){
map.put(str, 1);
}else{
map.put(str, value+1);
}
} else {
break;
}
}
reader.close();
}
private String getMostImportFile(){
Iterator<String> iter = map.keySet().iterator();
String result = "";
int max = 0;
while(iter.hasNext()){
String key = iter.next();
System.out.println(key+"-->"+map.get(key));
if(map.get(key)>max){
max = map.get(key);
result = key;
}
}
return result;
}
}