posts - 431,  comments - 344,  trackbacks - 0

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 周锐 阅读(837) 评论(0)  编辑  收藏 所属分类: Java

只有注册用户登录后才能发表评论。


网站导航: