经常碰到编译时出现classNotFound的情况,可是面对一大堆jar文件,又不知该将哪一个加到classpath.有没有办法根据提示缺少的类名搜索在哪个jar包中呢?
下面的程序就是实现这个功能的.(做了一些改进,原文有点小错误)
import java.io.File;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.List;
import java.util.zip.ZipEntry;
import java.util.zip.ZipFile;
public class FindInJar {
public String className;
public ArrayList jarFiles=new ArrayList();
public FindInJar(){
}
public FindInJar(String className){
this.className=className;
}
public void setClassName(String className){
this.className=className;
}
public List findClass(String dir,boolean recurse){
searchDir(dir,recurse);
return this.jarFiles;
}
protected void searchDir(String dir,boolean recurse){
try{
File d=new File(dir);
if(!d.isDirectory()){
return;
}
File[] files=d.listFiles();
for(int i=0;i<files.length;i++){
if(recurse && files[i].isDirectory()){
searchDir(files[i].getAbsolutePath(),true);
}else{
String filename=files[i].getAbsolutePath();
if(filename.endsWith(".jar") || filename.endsWith(".zip")){
ZipFile zip=new ZipFile(filename);
Enumeration entries=zip.entries();
while(entries.hasMoreElements()){
ZipEntry entry=(ZipEntry)entries.nextElement();
String thisClassName=getClassName(entry);
if(thisClassName.equals(this.className) || thisClassName.equals(this.className+".class")){
this.jarFiles.add(filename);
}
}
}
}
}
}catch(Exception e){
e.printStackTrace();
}
}
public List getFilename() {
return this.jarFiles;
}
protected String getClassName(ZipEntry entry){
StringBuffer className=new StringBuffer(entry.getName().replace('/','.'));
return className.toString();
}
public static void main(String args[]){
if(args.length<2){
System.out.println("Usage: FindInJar <ClassName> <Directory>");
return;
}
String classname=args[0];
String dirname=args[1];
FindInJar findInJar=new FindInJar(classname);
List jarFiles=findInJar.findClass(dirname,true);
if(jarFiles.size()==0){
System.out.println("Not Found.");
}else{
for(int i=0;i<jarFiles.size();i++){
System.out.println(jarFiles.get(i));
}
}
}
}
我在考虑将这个程序做成一个windows程序,采用可视化的操作界面,可以将要搜索的路径都添加进来,输入类名,
然后搜索.有时间再做吧.