3

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

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

But I don't know how to do it from an external jar.. can someone help me?

Nathan F.
  • 3,250
  • 3
  • 35
  • 69
  • does `bar` provide a way to access this file? if so, add it to the build path of `foo` and use the appropriate objects. – mre Nov 08 '12 at 17:40

2 Answers2

7

Use jar url to open connection the example 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;
  }
} 
Roman C
  • 49,761
  • 33
  • 66
  • 176
  • [This](http://stackoverflow.com/questions/13208999/how-can-i-retrieve-information-from-text-file-using-java-streams/13209144#13209144) information could be helpful for file IO. – Roman C Nov 10 '12 at 11:20
5

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

To read it from the jar use JarFile.getEntry and JarFile.getInputStream

Miserable Variable
  • 28,432
  • 15
  • 72
  • 133