Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Reading properties file from JAR directory

I’m creating an executable JAR that will read in a set of properties at runtime from a file. The directory structure will be something like:

/some/dirs/executable.jar
/some/dirs/executable.properties

Is there a way of setting the property loader class in the executable.jar file to load the properties from the directory that the jar is in, rather than hard-coding the directory.

I don't want to put the properties in the jar itself as the properties file needs to be configurable.

like image 778
Lehane Avatar asked Aug 19 '09 17:08

Lehane


1 Answers

Why not just pass the properties file as an argument to your main method? That way you can load the properties as follows:

public static void main(String[] args) throws IOException {
  Properties props = new Properties();
  props.load(new BufferedReader(new FileReader(args[0])));
  System.setProperties(props);
}

The alternative: If you want to get the current directory of your jar file you need to do something nasty like:

CodeSource codeSource = MyClass.class.getProtectionDomain().getCodeSource();
File jarFile = new File(codeSource.getLocation().toURI().getPath());
File jarDir = jarFile.getParentFile();

if (jarDir != null && jarDir.isDirectory()) {
  File propFile = new File(jarDir, "myFile.properties");
}

... where MyClass is a class from within your jar file. It's not something I'd recommend though - What if your app has multiple MyClass instances on the classpath in different jar files (each jar in a different directory)? i.e. You can never really guarantee that MyClass was loaded from the jar you think it was.

like image 187
Adamski Avatar answered Sep 25 '22 17:09

Adamski