一个jar文件夹中资源的列表?

7

通常情况下,我按照以下方式从jar文件中读取资源:

getClassLoader().getResource(pTextPath + "/" + pLang +".xml");

我需要从已知的jar文件夹中读取所有具有特定名称的资源。例如,从

addon/resources/texts

读取*.xml。
我能否通过路径和名称模板从jar文件中获取资源列表?
更新:与从类路径目录获取资源列表完全重复,请关闭问题。

1
在构建Jar文件时将列表放入其中,在运行时读取该列表。 - Andrew Thompson
4
获取类路径目录中的资源列表要获取类路径(classpath)目录中的所有资源,你可以使用以下代码:ClassLoader classLoader = Thread.currentThread().getContextClassLoader(); URL resourceUrl = classLoader.getResource("your/directory"); File directory = new File(resourceUrl.getFile()); File[] fileList = directory.listFiles();请注意,这将返回目录中的所有文件和子目录。如果你只想获取文件,你需要在 listFiles() 方法调用时过滤掉目录。另外,请确保目录名称正确,并且已经添加到了类路径中。 - jmj
1个回答

4
CodeSource src = MyClass.class.getProtectionDomain().getCodeSource();
if (src != null) {
  URL jar = src.getLocation();
ZipInputStream zip = new ZipInputStream(jar.openStream());
/* Now examine the ZIP file entries to find those you care about. */
 ...
} 
else {
   /* Fail... */
}

1
else { /* 失败... */ 代码在什么时候处理由Class.getProtectionDomain() 可能抛出的 SecurityException - Andrew Thompson

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接