user1991839
user1991839

Reputation: 2313

How to access a resource / configuration / text file in an external Jar from Java?

I am running a program in com.me.X.jar.

In an external com.me.Y.jar, I have a configuration file located at 'config/conf.txt' in the root of the Jar.

How can I access this configuration file programmatically from within Java?

com.me.Y.jar is not currently loaded in memory and is composed of just non-code resources.

Upvotes: 1

Views: 5733

Answers (3)

MadProgrammer
MadProgrammer

Reputation: 347334

The easiest option for reading embedded resources is to use Class.getResource or Class.getResourceAsStream

I can think of several ways to achieve this, depending on your needs.

Add the com.me.Y.jar to the classpath. You can do this either at the system level (not really recommended) or at the commend line...

java -cp com.me.Y.jar -jar com.me.X.jar

Edit It has being pointed at that apparently the -cp argument is ignored using the above command, but, if you include the main class it will work...java -cp com.me.Y.jar -jar com.me.X.jar com.me.x.Main (for example)

If that's inconvient, you can add com.me.Y.jar to com.me.X.jar manifest's class path which will automatically include com.me.Y.jar for you.

If you can't do that, you could use a URLClassLoader to directly load com.me.Y.jar...

URL[] urls = new URL[]{new File("/path/to/com.me.Y.jar").toURI().toURL())};
URLClassLoader classLoader = new URLClassLoader(urls);
URL resource = classLoader.findResource("/config/conf.txt");

Or, if you prefer, you could simply crack the Jar open using java.util.JarFile, but that seems a lot like cracking walnuts with a nuke...IMHO

Upvotes: 2

Andrew Thompson
Andrew Thompson

Reputation: 168845

Code to obtain URL

URL configURL = this.getClass().getResource("/config/conf.txt");

Manifest.mf of com.me.X.jar

See Adding Classes to the JAR File's Classpath.

Main-Class: ...
Class-Path: com.me.Y.jar

Upvotes: 1

MrSmith42
MrSmith42

Reputation: 10161

jar files are just zip files. So google for an example how to read a zip file. Or have a look at the API ZipInputStream

Upvotes: 2

Related Questions