Nicky Buttigieg
Nicky Buttigieg

Reputation: 21

Accessing getResourceAsStream() of jar dependency

I've got 2 projects; A and B (both maven projects). A is packaged as a jar and added as a dependency to project B. Both projects have a config.properties file located in their /resources folder. When running project B, the following code located in project A loads B's resources folder:

Properties configProps = new Properties();
    try {
        InputStream in = classInA.class.getResourceAsStream("/config.properties");
        BufferedReader br = new BufferedReader(new InputStreamReader(in));
        String line = null;
        while ((line = br.readLine()) != null)
        {
            String values[] = line.split("=", 2);
            configProps.setProperty(values[0], values[1]);
            line = br.readLine();
        }
    } catch (IOException e) {
        e.printStackTrace();
    }

I've got the same block of code in a method in project B, and that correctly access B's config.properties file. Any idea how I can fix this, or maybe you have a better idea on how to access files in jar dependencies both when ran as a jar as well as within the IDE (Intellij)

EDIT: Packages are as follows

No error stack is outputted since project B finds a config.properties file, however it is located in com.nicky.projectB/resources and not projectA's resources folder.

EDIT: Changing the filename of one of the properties seems to have solved the issue. I'm assuming it was first searching the parent project and defaulted to that properties file since they had the same name.

Upvotes: 1

Views: 972

Answers (1)

JB Nizet
JB Nizet

Reputation: 691685

getResourceAsStream("/config.properties") searches for the config.properties in the classpath, at the root.

It doesn't care whether the code calling the method is in A.jar or B.jar, and whether the file is in A.jar or B.jar.

It scans the classpath, and returns the first config.properties file found. If A.jar is before B.jar in the classspath, then A's config file will be returned. If B.jar is before A.jar in the classpath, then B's config file will be returned.

This problem is exactly why packages exist: to avoid name clashes. A's config file shouldn't be at the root. It should be in the same package as A's classes (com.mycompany.a, for example). And B's config file should be in the same package as B's classes (com.mycompany.b, for example).

Once you've correctly used packages that way, just as you're probably already doing for classes, you won't have name clashes anymore.

Upvotes: 1

Related Questions