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 周銳 閱讀(848) 評論(0)  編輯  收藏 所屬分類: Java
          主站蜘蛛池模板: 永康市| 克山县| 蒙城县| 贵定县| 兰考县| 长兴县| 禹州市| 吉林市| 炎陵县| 肇源县| 太和县| 东山县| 犍为县| 四会市| 毕节市| 五指山市| 台山市| 大新县| 比如县| 嘉禾县| 高要市| 开鲁县| 奇台县| 望城县| 安康市| 自贡市| 温州市| 左贡县| 鄂尔多斯市| 柳河县| 大新县| 合阳县| 武乡县| 阜宁县| 高台县| 汉中市| 永善县| 吉木乃县| 金平| 巴马| 临潭县|