我知道我们可以做这样的事情:
Class.class.getResourceAsStream("/com/youcompany/yourapp/module/someresource.conf")
以读取打包在我们的jar文件中的文件。
我已经在Google上搜索了很多,我肯定没有使用适当的术语;我要做的是列出可用资源,如下所示:
Class.class.listResources("/com/yourcompany/yourapp")
这应该返回包com.yourcompany.yourapp.*
内部的资源列表
有可能吗?关于如何做的任何想法,以防无法像我展示的那样容易完成?
注意:我知道有可能知道您的罐子在哪里,然后将其打开并检查其内容以达到目的。但是,我不能在现在工作的环境中这样做。
对于JAR文件中的资源,类似的方法有效:
URL url = MyClass.class.getResource("MyClass.class");
String scheme = url.getProtocol();
if (!"jar".equals(scheme))
throw new IllegalArgumentException("Unsupported scheme: " + scheme);
JarURLConnection con = (JarURLConnection) url.openConnection();
JarFile archive = con.getJarFile();
/* Search for the entries you care about. */
Enumeration<JarEntry> entries = archive.entries();
while (entries.hasMoreElements()) {
JarEntry entry = entries.nextElement();
if (entry.getName().startsWith("com/y/app/")) {
...
}
}
您可以使用文件系统或许多其他存储库中“爆炸”的资源执行相同的操作,但这并不是那么容易。您需要为每个要支持的URL方案指定代码。
通常无法获得像这样的资源列表。某些类加载器甚至可能都不支持该功能-想象一个可以从Web服务器获取单个文件的类加载器,但是Web服务器不必支持列出目录的内容。当然,对于jar文件,您可以显式加载jar文件的内容。([This question是相似的,顺便说一句。]