Will Smith
Will Smith

Reputation: 51

Read resources from specific JAR file (duplicate paths to file)

Let's say you have jar1 with artifactId zoo, and jar2 with artifactId animals. Both jars have a resource file with the same path (ex: /animals/animal.txt). Is there any way to read that file from a specific jar? Using getResourcesAsStream also returns the first jar but sometimes I want the second jar's animal.txt file.

Upvotes: 2

Views: 539

Answers (1)

df778899
df778899

Reputation: 10931

As @MadProgrammer suggests, ClassLoader.getResources() will return URLs, which look like jar:file:/C:/dir/animals.jar!/animals/animal.txt.

So this sort of excerpt should be able to choose the right file:

    Enumeration<URL> urls = getClass().getClassLoader().getResources("/animals/animal.txt");
    while (urls.hasMoreElements()) {
        URL url = urls.nextElement();
        if (url.toExternalForm().contains("animals.jar!")) {
            System.out.println(url);
            url.openStream()...
        }
    }

Upvotes: 1

Related Questions