Java: getting the right resource

I have a library foo.jarthat contains a file svnversion.properties(just looks like svnversion=12345Mor something else) and the following static method in class SVNVersion:

public static SVNVersion fromString(String s) { ... }
public static SVNVersion fromResources(Class<?> cl) {
    ResourceBundle svnversionResource = ResourceBundle.getBundle(
        "svnversion", Locale.getDefault(), cl.getClassLoader());
    if (svnversionResource.containsKey("svnversion"))
    {
        String svnv = svnversionResource.getString("svnversion");
        return fromString(svnv);
    }
    else
    {
        return null;
    }
}

I also have a library bar.jarthat contains a file svnversion.properties(say, contains svnversion=789).

However, when I run the following in class SomeClassInBarJar, which is in bar.jar:

SVNVersion vfoo = SVNVersion.fromResources(SVNVersion.class);
SVNVersion vbar = SVNVersion.fromResources(SomeClassInBarJar.class);

and I print the result, I see 789twice. Clearly, I am not doing it right. How to get the correct file svnversion.propertiesin the root jar file containing this class? (assuming it is there)


edit: I just tried

InputStream is = cl.getResourceAsStream("/svnversion.properties");

and has the same problem. It seems I can access the main jar file /svnversion.properties, not the library /svnversion.properties.

+3
1

, , , svnversion.properties . , : , , .

A () , jar, svnversion.properties :

public static JarFile getJarFile(Class<?> cl) {
    URL classUrl = cl.getResource(cl.getSimpleName() + ".class");
    if (classUrl != null) {
        try {
            URLConnection conn = classUrl.openConnection();
            if (conn instanceof JarURLConnection) {
                JarURLConnection connection = (JarURLConnection) conn;
                return connection.getJarFile();
            }
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }
    return null;
}

public static SVNVersion fromResources(Class<?> cl) {
    JarFile jarFile = getJarFile(cl);
    ZipEntry entry = jarFile.getEntry("svnversion.properties");
    Properties props = new Properties();
    try {
        props.load(jarFile.getInputStream(entry));
    } catch (IOException e) {
        throw new RuntimeException(e);
    }

    if (props.containsKey("svnversion")) {
        String svnv = props.getProperty("svnversion");
        return fromString(svnv);
    } else {
        return null;
    }
}

IMHO, , svn ( svn $Revision$).

+2

Source: https://habr.com/ru/post/1785499/


All Articles