Shengjie
Shengjie

Reputation: 12796

Execute a jar with an external properties file

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.

Upvotes: 3

Views: 12442

Answers (2)

JitenS
JitenS

Reputation: 51

One sample example

@Echo off
java -cp "C:/***/***" -Dlog4j.configuration=file:C:/***/***/log4j.properties com.****.****.MainMethod %1 %2 ...
pause

Upvotes: 0

Dave Newton
Dave Newton

Reputation: 160291

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.

Upvotes: 5

Related Questions