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 getfilenames() {
return this.jarfiles;
}
protected string getclassname(zipentry entry) {
stringbuffer classname = new stringbuffer(entry.getname().replace(’/', ‘.’));
return classname.tostring();
}
public static void main(string args[]) {
findinjar findinjar = new findinjar("javax.mail.session");
list jarfiles = findinjar.findclass("d:/libs/", 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));
}
}
}
}
main方法中的findclass方法的第二个参数是是否对指定的目录递归进行处理,一般都会要这样做的吧。