Get the file in the bank in the bank

I have a setting like this:

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

So, I execute external.jar and inside it the 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 definitely exists. Is this not possible with JarURLConnection?

+6
source share
2 answers

In the end, we used the Maven Shade plugin ( http://maven.apache.org/plugins/maven-shade-plugin/ ).

+1
source

Jar files are simply a simpler version of Zip files with a different name, so you just need to consider 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 is problem since it is not recommended to have jar files attached.

(Why don't you combine them?)

+2
source

Source: https://habr.com/ru/post/972978/


All Articles