I have a setup like this:
So, I am executing outer.jar and within it's main class:
URL url = Main.class.getClassLoader().getResource("file.txt");
url is: '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?
JAR files work just like ZIP files. You can use any archive program to extract them. On Windows, you can Install WinRAR 7-Zip, or WinZIP.
Jar files are just simpler version of Zip files with other name, so it's just a matter of treating them as zip files:
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.
(Why don't you merge them?)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With