posts - 431,  comments - 344,  trackbacks - 0

          URLClassLoader
              該類加載器用于從指向 JAR 文件和目錄的 URL 的搜索路徑加載類和資源。這里假定任何以 '/' 結(jié)束的 URL 都是指向目錄的。如果不是以該字符結(jié)束,則認為該 URL 指向一個將根據(jù)需要打開的 JAR 文件。 
              注意: 如果在傳遞URL的時候使用磁盤路徑的時候需要加上"file:/"前綴.

          JarFile
          JarFile 類用于從任何可以使用 Java.io.RandomAccessFile 打開的文件中讀取 jar 文件的內(nèi)容。它擴展了 Java.util.zip.ZipFile 類,使之支持讀取可選的 Manifest 條目。Manifest 可用于指定關(guān)于 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 周銳 閱讀(846) 評論(0)  編輯  收藏 所屬分類: Java
          主站蜘蛛池模板: 定陶县| 桃园县| 子长县| 林甸县| 东光县| 元朗区| 白水县| 宝清县| 抚州市| 延安市| 鹿泉市| 乐陵市| 蕉岭县| 沙湾县| 沁水县| 德清县| 鹤壁市| 芦山县| 镇原县| 温泉县| 鄂伦春自治旗| 汉中市| 安顺市| 青铜峡市| 依安县| 涞源县| 陆良县| 桐城市| 巴东县| 五台县| 策勒县| 贵阳市| 诸暨市| 高清| 远安县| 清徐县| 西华县| 庆城县| 临猗县| 武义县| 天等县|