user8072194
user8072194

Reputation:

Read external properties file Java/Linux

I've been tasked with writing some code that will pull a properties file depending on which environment I'm in (production or testing). So the jar file will be the same in each environment, but some variable will change depending on which environment the jar is executed. The director will look like this:

[ProgramOne.jar ProgramTwo.jar ProgramThree.jar mypropertiesfile.properties]

I need each one of those jars to read in the properties file. I am reading things in like this:

   try(InputStream theResourceStream = Thread.currentThread().getContextClassLoader().getResourceAsStream("mypropertiesfile.properties"))

I do not have access to these environments yet, and will have a VERY small window in order to implement this code. My question is, is this the correct way to read in a properties file given my situation? Will this even work? I have tried this loading the file on my local machine but everything comes back null.

Upvotes: 0

Views: 1812

Answers (1)

xtratic
xtratic

Reputation: 4699

If it doesn't work on your machine then it likely wont work on the other machine.

It looks like you are trying to load a resource from the Jar when I think you want to load properties from an external file in the same directory.

Try this instead:
with test.properties in the same directory as the Jar, with a property my-property=this is a test

public class Main {
    public static void main(String[] args){ new Main().test(); }

    /** Usually gets the `JAR` directory or the `bin` when running in IDE */
    public String getCodeSourcePath() throws SecurityException, URISyntaxException {
        return getClass().getProtectionDomain().getCodeSource().getLocation()
            .toURI().getPath();
    }

    public void test() {
        // TODO handle exceptions, unlikely to occur unless you do something weird
        String jarPath = getCodeSourcePath();

        Properties properties = new Properties();
        File file = new File(jarPath, "test.properties");
        try (FileInputStream fis = new FileInputStream(file);) {
            properties.load(fis);
        }
        System.out.println(properties.getProperty("my-property"));

    }
}

Output: this is a test

Upvotes: 2

Related Questions