你好,欢迎来到电脑编程技巧与维护杂志社! 杂志社简介广告服务读者反馈编程社区  
合订本订阅
 
 
您的位置:技术专栏 / Linux开发
从JAR和ZIP档案文件中提取Java资源讲解(2)
 

现在,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();
    }
  }

(编辑:aniston)

  推荐精品文章

·2024年12月目录 
·2024年11月目录 
·2024年10月目录 
·2024年9月目录 
·2024年8月目录 
·2024年7月目录 
·2024年6月目录 
·2024年5月目录 
·2024年4月目录 
·2024年3月目录 
·2024年2月目录 
·2024年1月目录
·2023年12月目录
·2023年11月目录

  联系方式
TEL:010-82561037
Fax: 010-82561614
QQ: 100164630
Mail:gaojian@comprg.com.cn

  友情链接
 
Copyright 2001-2010, www.comprg.com.cn, All Rights Reserved
京ICP备14022230号-1,电话/传真:010-82561037 82561614 ,Mail:gaojian@comprg.com.cn
地址:北京市海淀区远大路20号宝蓝大厦E座704,邮编:100089