URLClassLoader
該類加載器用于從指向 JAR 文件和目錄的 URL 的搜索路徑加載類和資源。這里假定任何以 '/' 結束的 URL 都是指向目錄的。如果不是以該字符結束,則認為該 URL 指向一個將根據需要打開的 JAR 文件。
注意: 如果在傳遞URL的時候使用磁盤路徑的時候需要加上"file:/"前綴.
JarFile
JarFile
類用于從任何可以使用 Java.io.RandomAccessFile
打開的文件中讀取 jar 文件的內容。它擴展了 Java.util.zip.ZipFile
類,使之支持讀取可選的 Manifest
條目。Manifest
可用于指定關于 jar 文件及其條目的元信息。
主要代碼如下:
package com.founder.test;
import Java.io.File;
import Java.io.IOException;
import Java.net.MalformedURLException;
import Java.net.URL;
import Java.net.URLClassLoader;
import Java.util.ArrayList;
import Java.util.Enumeration;
import Java.util.List;
import Java.util.jar.JarEntry;
import Java.util.jar.JarFile;
public class ReadDriverUtil {
public static List<String> getDriverNames(String jarPath) {
URLClassLoader clazzLoader;
List<String> driverNames = new ArrayList<String>();
try {
clazzLoader = new URLClassLoader(new URL[]{new URL("file:/" + jarPath)});
JarFile jarFile = new JarFile(new File(jarPath));
Enumeration<JarEntry> entries = jarFile.entries();
List<String> classNames = new ArrayList<String>();
while (entries.hasMoreElements()) {
JarEntry entry = entries.nextElement();
if (!entry.isDirectory() && entry.getName().endsWith(".class") && entry.getName().toLowerCase().indexOf("driver") != -1) {
int index = entry.getName().indexOf(".class");
classNames.add(entry.getName().replaceAll("/", ".").substring(0, index));
}
}
for(String className : classNames) {
try {
Class clz = clazzLoader.loadClass(className);
if (java.sql.Driver.class.isAssignableFrom(clz)) {
driverNames.add(className);
}
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
}
} catch (MalformedURLException e1) {
e1.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return driverNames;
}
}
posted on 2009-05-26 15:58
周銳 閱讀(845)
評論(0) 編輯 收藏 所屬分類:
Java