在目录中查找java类位于哪个jar包中,这个是我从网上查钱的资

 1 //在目录中查找java类位于哪个jar包中,这个是我从网上查钱的资料,试了一下,很不错。
 2 
 3 import java.io.File;
 4 import java.util.ArrayList;
 5 import java.util.Enumeration;
 6 import java.util.List;
 7 import java.util.zip.ZipEntry;
 8 import java.util.zip.ZipFile;
 9 
10 public class FindInJar {
11     public String className;
12 
13     public ArrayList<String> jarFiles = new ArrayList<String>();
14 
15     public FindInJar() {
16     }
17 
18     public FindInJar(String className) {
19         this.className = className;
20     }
21 
22     public void setClassName(String className) {
23         this.className = className;
24     }
25 
26     public List<String> findClass(String dir, boolean recurse) {
27         searchDir(dir, recurse);
28         return this.jarFiles;
29     }
30 
31     protected void searchDir(String dir, boolean recurse) {
32         try {
33             File d = new File(dir);
34             if (!d.isDirectory()) {
35                 return;
36             }
37             File[] files = d.listFiles();
38             for (int i = 0; i < files.length; i++) {
39                 if (recurse && files[i].isDirectory()) {
40                     searchDir(files[i].getAbsolutePath(), true);
41                 } else {
42                     String filename = files[i].getAbsolutePath();
43                     if (filename.endsWith(".jar")||filename.endsWith(".zip")) {
44                         ZipFile zip = new ZipFile(filename);
45                         Enumeration entries = zip.entries();
46                         while (entries.hasMoreElements()) {
47                             ZipEntry entry = (ZipEntry) entries.nextElement();
48                             String thisClassName = getClassName(entry);
49                             if (thisClassName.equals(this.className) || thisClassName.equals(this.className + ".class")) {
50                                 this.jarFiles.add(filename);
51                             }
52                         }
53                     }
54                 }
55             }
56         } catch (Exception e) {
57             e.printStackTrace();
58         }
59     }
60 
61     public List<String> getFilenames() {
62         return this.jarFiles;
63     }
64 
65     protected String getClassName(ZipEntry entry) {
66         StringBuffer className = new StringBuffer(entry.getName().replace('/', '.'));
67         return className.toString();
68     }
69 
70     public static void main(String args[]) {
71         FindInJar findInJar = new FindInJar("com.microsoft.sqlserver.jdbc.SQLServerDriver");
72         List<String> jarFiles = findInJar.findClass("D:/workspace/CiscoYearendTool/WebRoot/WEB-INF/lib", true);
73         if (jarFiles.size() == 0) {
74             System.out.println("Not Found");
75         } else {
76             for (int i = 0; i < jarFiles.size(); i++) {
77                 System.out.println(jarFiles.get(i));
78             }
79         }
80     }
81 }

 

料,试了一下,很不错。