J Fabian Meier
J Fabian Meier

Reputation: 35785

Access properties file in same jar

All our jars contain a certain file version.properties which contains specific information from the build.

When we start a jar from command line (with several jars on the class path), we would like access the version.properties from the same jar. To be more precise: We would like to write Java code that gives us the content of the properties file in the jar where the calling class file resides.

The problem is that all jars on the class path contain version.properties and we do not want to read the first on the class path but the one from the correct jar. How can we achieve that?

Upvotes: 1

Views: 406

Answers (1)

Lothar
Lothar

Reputation: 5449

Funny problem. You have to find the location of a representative class of the particular jar and use the result to build the URL for the properties file. I hacked together an example using String.class as example and access MANIFEST.MF in META-INF, since the rt.jar has no properties in it (at least a quick jar tf rt.jar | grep properties resulted in zero results)

    Class clazz = String.class;
    String name = clazz.getName().replace('.', '/') + ".class";
    System.out.println(name);
    String loc = clazz.getClassLoader().getResource(name).toString();
    System.out.println(loc);
    if (loc.startsWith("jar:file")) {
        String propertyResource = loc.substring(0, loc.indexOf('!')) + "!" + "/META-INF/MANIFEST.MF";
        InputStream is = new URL(propertyResource).openStream();
        System.out.println(propertyResource);
        Properties props = new Properties();
        props.load(is);
        System.out.println(props.get("Implementation-Title"));
    }

Upvotes: 2

Related Questions