[英]Get a file in a jar in jar
I have a setup like this: 我有这样的设置:
So, I am executing outer.jar and within it's main class: 所以,我正在执行outer.jar并在它的主类中:
URL url = Main.class.getClassLoader().getResource("file.txt");
url is: 'jar:file:outer.jar!/inner.jar!/file.txt' url是:'jar:file:outer.jar!/inner.jar!/file.txt'
But if I try to read it like: 但是,如果我尝试阅读它:
url.openStream()
I get an exception 我得到一个例外
Exception in thread "main" java.io.FileNotFoundException: JAR entry inner.jar!/file.txt not found in outer.jar
at sun.net.www.protocol.jar.JarURLConnection.connect(JarURLConnection.java:142)
at sun.net.www.protocol.jar.JarURLConnection.getInputStream(JarURLConnection.java:150)
at java.net.URL.openStream(URL.java:1038)
at Main.main(Main.java:15)
The file is definitely there. 文件肯定在那里。 Is this not possible with JarURLConnection?
JarURLConnection是不可能的?
Jar files are just simpler version of Zip files with other name, so it's just a matter of treating them as zip files: Jar文件只是具有其他名称的Zip文件的简单版本,因此只需将它们视为zip文件:
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.util.Enumeration;
import java.util.zip.ZipEntry;
import java.util.zip.ZipFile;
public class Main{
public static void main(String[] args) throws IOException {
URL url = Main.class.getResource("file.jar");
ZipFile zipFile = new ZipFile(url.getFile());
Enumeration<? extends ZipEntry> entries = zipFile.entries();
while(entries.hasMoreElements()){
ZipEntry entry = entries.nextElement();
//InputStream stream = zipFile.getInputStream(entry); <- to handle the file
//print the names of the files inside the Jar
System.out.println(entry.getName());
}
}
}
NOTE: This appears to be a design problem as it isn't recommended to have nested jar files. 注意:这似乎是一个设计问题 ,因为不建议使用嵌套的jar文件。
(Why don't you merge them?) (你为什么不把它们合并?)
我们最终使用了Maven Shade插件( http://maven.apache.org/plugins/maven-shade-plugin/ )。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.