Nathan F.
Nathan F.

Reputation: 3469

Read a file from inside of an external Jar file?

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

Upvotes: 3

Views: 9493

Answers (2)

Roman C
Roman C

Reputation: 1

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;
  }
} 

Start reading the tutorials and look at examples for text file IO. Use FileReader with BufferedReader may also bridging with InputStreamReader if you need to adjust to specific locale. For output you could use text Formatter to format text specified by pattern, or just use console printf().

Upvotes: 7

Miserable Variable
Miserable Variable

Reputation: 28752

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

Upvotes: 5

Related Questions