java 从jar中读取文件 三种方法<Enumeration>

  • Sample1-利用Manifest文件读取jar中的文件

1.文件目录
test--
--a.text
--b.gif

2. Menifest文件内容:
Manifest-Version: 1.0
abc: test/a.txt
iconname: test/Anya.jpg
注意:manifest.mf文件最后一行要打一回车
Another Notification:
如果manifest文件内容是:
Manifest-Version: 1.0
Main-Class: com.DesignToolApp
Class-path: lib/client.jar lib/j2ee.jar
在MANIFEST.MF文件的最后,要留两个空行(也就是回车),才可以识别到Class-Path这一行,如果只有一个空行,那么只识别到Main- Class这一行。Class-Path中的库名用空格格开,使用和jar包相对的路径,发布时把jar包和其他用到的类库一起交给用户就可以了。


3.打jar包
test.jar

Java代码 收藏代码
  1. Stringiconpath=jar.getManifest().getMainAttributes().getValue("abc");
  2. InputStreamin=jar.getInputStream(jar.getJarEntry(iconpath));
  3. //Imageimg=ImageIO.read(in);
  4. InputStreamReaderisr=newInputStreamReader(in);
  5. BufferedReaderreader=newBufferedReader(isr);
  6. Stringline;
  7. while((line=reader.readLine())!=null){
  8. System.out.println(line);
  9. }
  10. reader.close();

  • Sample2,读取JAR 文件列表及各项的名称、大小和压缩后的大小

Java代码 收藏代码
  1. publicclassJarFileInfoRead{
  2. publicstaticvoidmain(Stringargs[])throwsIOException{
  3. Stringjarpath="d://temp//test.jar";
  4. JarFilejarFile=newJarFile(jarpath);
  5. Enumerationenu=jarFile.entries();
  6. while(enu.hasMoreElements()){
  7. process(enu.nextElement());
  8. }
  9. }
  10. privatestaticvoidprocess(Objectobj){
  11. JarEntryentry=(JarEntry)obj;
  12. Stringname=entry.getName();
  13. longsize=entry.getSize();
  14. longcompressedSize=entry.getCompressedSize();
  15. System.out.println(name+"\t"+size+"\t"+compressedSize);
  16. }
  17. }

  • Sample3,读取JAR中 文件的内容
Java代码 收藏代码
  1. publicclassJarFileRead{
  2. publicstaticvoidmain(Stringargs[])
  3. throwsIOException{
  4. Stringjarpath="d://temp//test.jar";
  5. JarFilejarFile=newJarFile(jarpath);
  6. Enumerationenu=jarFile.entries();
  7. while(enu.hasMoreElements()){
  8. JarEntryentry=(JarEntry)enu.nextElement();
  9. Stringname=entry.getName();
  10. //System.out.println(name);
  11. if(name.equals("test/a.txt")){
  12. InputStreaminput=jarFile.getInputStream(entry);
  13. process(input);
  14. }
  15. }
  16. jarFile.close();
  17. }
  18. privatestaticvoidprocess(InputStreaminput)
  19. throwsIOException{
  20. InputStreamReaderisr=
  21. newInputStreamReader(input);
  22. BufferedReaderreader=newBufferedReader(isr);
  23. Stringline;
  24. while((line=reader.readLine())!=null){
  25. System.out.println(line);
  26. }
  27. reader.close();
  28. }
  29. }
转自:http://dcriori.iteye.com/blog/570082
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值