从JAR和ZIP档案文件中提取Java资源讲解

豆豆网   技术应用频道   2007年09月03日  【字号: 收藏本文

内容摘要:本文将回答这个问题,并会提供一个类,这个类使从 jar 文件中提取任何资源变得非常简单!

  现在,init()方法只将指定 jar 文件的整个内容加载到一个 hashtable(通过资源名访问)中。

  这是一个相当有用的方法,下面我们对它作进一步的分析。ZipFile类为我们提供了对 jar/zip 档案头信息的基本访问方法。这类似于文件系统中的目录信息。下面我们列出ZipFile中的所有条目,并用档案中每个资源的大小添充 htsizes hashtable:

private void init() {
   try {
     // extracts just sizes only.
     ZipFile zf=new ZipFile(jarFileName);
     Enumeration e=zf.entries();
     while (e.hasMoreElements()) {
       ZipEntry ze=(ZipEntry)e.nextElement();
       if (debugOn) {
         System.out.println(dumpZipEntry(ze));
       }
       htSizes.put(ze.getName(),new Integer((int)ze.getSize()));
     }
     zf.close();

  接下来,我们使用ZipInputStream类访问档案。ZipInputStream类完成了全部魔术,允许我们单独读取档案中的每个资源。我们从档案中读取组成每个资源的精确字节数,并将其存储在 htjarcontents hashtable 中,您可以通过资源名访问这些数据:

// extract resources and put them into the hashtable.
     FileInputStream fis=new FileInputStream(jarFileName);
     BufferedInputStream bis=new BufferedInputStream(fis);
     ZipInputStream zis=new ZipInputStream(bis);
     ZipEntry ze=null;
     while ((ze=zis.getNextEntry())!=null) {
       if (ze.isDirectory()) {
        continue;////啊哟!没有处理子目录中的资源啊
       }
       if (debugOn) {
        System.out.println(
          "ze.getName()="+ze.getName()+","+"getSize()="+ze.getSize()
          );
       }
       int size=(int)ze.getSize();
       // -1 means unknown size.
       if (size==-1) {
        size=((Integer)htSizes.get(ze.getName())).intValue();
       }
       byte[] b=new byte[(int)size];
       int rb=0;
       int chunk=0;
      while (((int)size - rb) > 0) {
         chunk=zis.read(b,rb,(int)size - rb);
         if (chunk==-1) {
          break;
         }
         rb+=chunk;
       }
       // add to internal resource hashtable
       htJarContents.put(ze.getName(),b);
       if (debugOn) {
        System.out.println(
          ze.getName()+" rb="+rb+
          ",size="+size+
          ",csize="+ze.getCompressedSize()
          );
       }
     }
    } catch (NullPointerException e) {
     System.out.println("done.");
    } catch (FileNotFoundException e) {
     e.printStackTrace();
    } catch (IOException e) {
     e.printStackTrace();
    }
  }

责编:豆豆技术应用

正在加载评论...