从特定的JAR文件中读取资源(文件的重复路径) [英] Read resources from specific JAR file (duplicate paths to file)
问题描述
比方说,您的jar1带有artifactId动物园,而jar2则带有artifactId动物.这两个jar都有一个具有相同路径的资源文件(例如:/animals/animal.txt).有什么方法可以从特定的jar中读取该文件?使用getResourcesAsStream还可以返回第一个jar,但有时我想要第二个jar的animal.txt文件.
Let's say you have jar1 with artifactId zoo, and jar2 with artifactId animals. Both jars have a resource file with the same path (ex: /animals/animal.txt). Is there any way to read that file from a specific jar? Using getResourcesAsStream also returns the first jar but sometimes I want the second jar's animal.txt file.
推荐答案
按照@MadProgrammer的建议,ClassLoader.getResources()
将返回类似于jar:file:/C:/dir/animals.jar!/animals/animal.txt
的URL.
As @MadProgrammer suggests, ClassLoader.getResources()
will return URLs, which look like jar:file:/C:/dir/animals.jar!/animals/animal.txt
.
因此,此类摘录应该能够选择正确的文件:
So this sort of excerpt should be able to choose the right file:
Enumeration<URL> urls = getClass().getClassLoader().getResources("/animals/animal.txt");
while (urls.hasMoreElements()) {
URL url = urls.nextElement();
if (url.toExternalForm().contains("animals.jar!")) {
System.out.println(url);
url.openStream()...
}
}
这篇关于从特定的JAR文件中读取资源(文件的重复路径)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!