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

请注意,用来标识每个资源的名称是档案中资源的限定路径名,例如,不是包中的类名 -- 即 java.util.zip 包中的ZipEntry类将被命名为 "java/util/zip/ZipEntry",而不是 "java.util.zip.ZipEntry"。

  其它方法:

/**
  * Dumps a zip entry into a string.
  * @param ze a ZipEntry
  */
  private String dumpZipEntry(ZipEntry ze) {
    StringBuffer sb=new StringBuffer();
    if (ze.isDirectory()) {
     sb.append("d ");
    } else {
     sb.append("f ");
    }
    if (ze.getMethod()==ZipEntry.STORED) {
     sb.append("stored  ");
    } else {
     sb.append("defalted ");
    }
    sb.append(ze.getName());
    sb.append("  ");
    sb.append(""+ze.getSize());
    if (ze.getMethod()==ZipEntry.DEFLATED) {
     sb.append("/"+ze.getCompressedSize());
    }
    return (sb.toString());
  }
  /**
  * Extracts a jar resource as a blob.
  * @param name a resource name.
  */
  public byte[] getResource(String name) {
   return (byte[])htJarContents.get(name);
  }

  代码的最后一个重要部分是简单的测试驱动程序。该测试驱动程序是一个简单的应用程序,它接收 jar/zip 档案名和资源名。它试图发现档案中的资源文件,然后将成功或失败的消息报告出来:

public static void main(String[] args) throws IOException {
    if (args.length!=2) {
     System.err.println(
       "usage: java JarResources < jar file name> < resource name>"
       );
     System.exit(1);
    }
    JarResources jr=new JarResources(args[0]);
    byte[] buff=jr.getResource(args[1]);
    if (buff==null) {
     System.out.println("Could not find "+args[1]+".");
    } else {
     System.out.println("Found "+args[1]+ " (length="+buff.length+").");
    }
  }
}  // End of JarResources class.

  您已了解了这个类。一个易于使用的类,它隐藏了使用打包在 jar 文件中的资源的全部棘手问题。

  小结

  如果您曾经渴望知道如何从 jar 文件中提取图像,那么您现在已学到了一种方法。有了本技巧提供的这个新类,您就不仅可以用 jar 文件处理图像,而且可以将提取魔术用于 jar 文件中的任何资源。

(编辑: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