Execute a jar with an external properties file

11,191

Once you specify -jar all classpath options are ignored.

Instead, specify a default config location (like in user's home directory) and allow overriding on the command line.

There are a variety of command line parsing options, the easiest annotate class properties with option information, e.g., the long and short option names, usage, etc.

Or use a -D option and retrieve the appropriate system property.

Another option is the Preferences API.

Share:
11,191
Shengjie
Author by

Shengjie

Enthusiastic software engineer, a big fan of open source community development, big data, cloud technologies etc...

Updated on June 05, 2022

Comments

  • Shengjie
    Shengjie almost 2 years

    I have a jar with main-class which can be executed like: java -jar test.jar

    Inside the jar I have something like

    public static void main(String[] args) throws IOException {
        InputStream is = ClassLoader.getSystemClassLoader().getResourceAsStream("config.properties");
        Properties prop = new Properties();
        prop.load(is);
        //then I wanna fetch all the properties in the config.properties file
    }
    

    I run both:

    1. java -jar test.jar

    2. java -jar test.jar -cp /tmp (where config.properties is located)

    3. java -jar test.jar -cp /tmp/config.properties (obviously it doesn't work, but give you the idea what I am trying to achieve here)

    The code didn't work, all three throw NPE although I put the path of the config.properties file under my $PATH and $CLASSPATH.

    The point is that, in long run, I will put the configuration file in ${my-config-path}, and read/handle it properly. But temporally I just want something quick and dirty.

    1. I DO NOT want to include the properties file in my jar.
    2. I want to keep it externally in the classpath or path, when I execute the jar, it locates it without issues.