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

查看:26
本文介绍了如何列出 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 读取它.

Granted I could read it using 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天全站免登陆