如何列出JAR文件中的文件? [英] How to list the files inside a JAR file?

查看:125
本文介绍了如何列出JAR文件中的文件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这段代码可以从目录中读取所有文件.

I have this code which reads all the files from a directory.

    File textFolder = new File("text_directory");

    File [] texFiles = textFolder.listFiles( new FileFilter() {
           public boolean accept( File file ) {
               return file.getName().endsWith(".txt");
           }
    });

效果很好.它使用目录"text_directory"中所有以".txt"结尾的文件填充数组.

It works great. It fills the array with all the files that end with ".txt" from directory "text_directory".

如何在JAR文件中 以类似的方式读取目录的内容?

How can I read the contents of a directory in a similar fashion within a JAR file?

所以我真正想做的是列出我的JAR文件中的所有图像,这样我就可以加载它们:

So what I really want to do is, to list all the images inside my JAR file, so I can load them with:

ImageIO.read(this.getClass().getResource("CompanyLogo.png"));

(之所以可行,是因为"CompanyLogo"是硬编码的",但是JAR文件中的图像数量可能是10到200个可变长度.)

(That one works because the "CompanyLogo" is "hardcoded" but the number of images inside the JAR file could be from 10 to 200 variable length.)

编辑

所以我想我的主要问题是:如何知道我的主要班级所在的 JAR文件的名称?

So I guess my main problem would be: How to know the name of the JAR file where my main class lives?

我可以使用java.util.Zip读取它.

我的结构是这样的:

它们就像:

my.jar!/Main.class
my.jar!/Aux.class
my.jar!/Other.class
my.jar!/images/image01.png
my.jar!/images/image02a.png
my.jar!/images/imwge034.png
my.jar!/images/imagAe01q.png
my.jar!/META-INF/manifest 

现在,我可以使用以下方式加载例如"images/image01.png":

Right now I'm able to load for instance "images/image01.png" using:

    ImageIO.read(this.getClass().getResource("images/image01.png));

但是仅仅因为我知道文件名,其余的我必须动态地加载它们.

But only because I know the file name, for the rest I have to load them dynamically.

推荐答案

CodeSource src = MyClass.class.getProtectionDomain().getCodeSource();
if (src != null) {
  URL jar = src.getLocation();
  ZipInputStream zip = new ZipInputStream(jar.openStream());
  while(true) {
    ZipEntry e = zip.getNextEntry();
    if (e == null)
      break;
    String name = e.getName();
    if (name.startsWith("path/to/your/dir/")) {
      /* Do something with this entry. */
      ...
    }
  }
} 
else {
  /* Fail... */
}

请注意,在Java 7中,您可以从JAR(zip)文件创建FileSystem,然后使用NIO的目录遍历和过滤机制在其中搜索.这样可以更轻松地编写处理JAR和爆炸"目录的代码.

Note that in Java 7, you can create a FileSystem from the JAR (zip) file, and then use NIO's directory walking and filtering mechanisms to search through it. This would make it easier to write code that handles JARs and "exploded" directories.

这篇关于如何列出JAR文件中的文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆