Search code examples
javajarlookupmanifest.mfmeta-inf

Howto: Locate a Resource file within a JAR file without knowing the name and location upfront


General problem: finding/locating a resource file (document.xml) within a JAR file that has no fixed position where it can be found and even the name of the file is unknown upfront.

Situation: two JavaSE projects, both create own JAR file. Jar-A holds a xml document somewhere within the jar (location not known upfront). Jar-B wants to ask JarA to hand over the document for a certain operation (e.g. settings information). The caller, Jar-B doesn't know how what the resource/file is called, and where its current location within Jar-A is.

Requirements: Jar-B should be dependent of fixed locations of resources/files in Jar-A because resources can be renamed or moved around within Jar-A. Jar-B should ask Jar-A where the file is and how the file is called it is looking for.

Possible solution direction: The META-INF directory always holds a MANIFETS.MF file with key/value pairs. So, if I store a key called 'ResourceLocator' and a value like 'org.my.package.ResourceLocator.class', then Jar-B can find the class it can load to instantiate a locator object that can give out the correct name and location of the file it is looking for, right?

The resourcelocator can be used for more values to be looked up this way.

Having a resourcelocator object within Jar-A, only the keys to reference to 'things' need to be documented, but the actual implementation is decoupled from the outside world.

I am wondering if this is a good approach to deal with this kind of lookup? I already know about the Netbeans Lookup API, but that needs a class/interface name for the lookup. That is not what I am looking for right now.

Any ideas how to make sure the Jar-A and Jar-B stay decoupled when searching for resources not known upfront?

Note: this is not some service loader or extersion mechanism, because that would be the other way around: Jar-B needs to be found by Jar-A. Which is not the case here. Jar-A doesn't know of any existence of Jar-B.

Hopefully someone came across this 'problem' already. Please share your ideas... Thanks!

Link to JAR Specs: here


Solution

  • JARs are ZIPs. Java has decent native support - seems solid enough - to open JAR-A and paw through the files inside (ZipFile.entries Enumeration.)

    That assumes you can locate JAR-A on the filesystem, which from the sound of your description, I'nm guessing that JAB-B knows exactly where JAR-A is located.