Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get a file in a jar in jar

Tags:

java

jar

I have a setup like this:

  • outer.jar
    • inner.jar
      • file.txt

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?

like image 997
dontocsata Avatar asked Jul 28 '14 18:07

dontocsata


People also ask

Can you extract a JAR file?

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.


1 Answers

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?)

like image 105
Mansueli Avatar answered Oct 09 '22 16:10

Mansueli