Read file from external jar file?

I am trying to read a file from an external jar using java .. For example, I have two jar files. One of them is "foo.jar", the other is "bar.jar". Inside the "bar.jar" is the file "foo-bar.txt". How can I read the file "foo-bar.txt" from inside "bar.jar" using the code in "foo.jar" ...? Is it even possible ..? I know that I can read the file from iside foo.jar using

this.getClass().getClassLoader().getResourceAsStream("foo-bar.txt"); 

But I do not know how to do this from an external can. Can someone help me?

+2
source share
2 answers

Use jar url to open connection sample code

 InputStream in = null; String inputFile = "jar:file:/c:/path/to/my.jar!/myfile.txt"; if (inputFile.startsWith("jar:")){ try { inputURL = new URL(inputFile); JarURLConnection conn = (JarURLConnection)inputURL.openConnection(); in = conn.getInputStream(); } catch (MalformedURLException e1) { System.err.println("Malformed input URL: "+inputURL); return; } catch (IOException e1) { System.err.println("IO error open connection"); return; } } 
+2
source

If the jar is in your getResourceAsStream path getResourceAsStream then getResourceAsStream will work, but note that it will find the first instance in your class path. If foo.jar and bar.jar both contain this file, then it will return which jar will be first in the classpath.

To read it from a jar, use JarFile.getEntry and JarFile.getInputStream

+5
source

All Articles