Saturday, April 27, 2013

Adding Java System Properties from a Properties File

Apache Commons Configuration provides a very easy way to load a properties file into the system properties:
try {
  final PropertiesConfiguration propsConfig = new PropertiesConfiguration(
                                              Foo.class.getResource("foo.properties"));
  SystemConfiguration.setSystemProperties(propsConfig);
} catch (Exception e) {
  throw new RuntimeException("Failed to load config file: " + propsFile, e);
}
If you are unable to use this library, then you will have to use the longer, more tedious approach of loading the properties file, iterating over the properties and setting each one into the system properties. This is shown below:
final Properties props = new Properties();
final InputStream in = Foo.class.getResourceAsStream("foo.properties");
try {
  props.load(in);
  for (final Entry<Object, Object> entry : props.entrySet()) {
    System.setProperty(entry.getKey().toString(), entry.getValue().toString());
  }
} catch (IOException e) {
  throw new RuntimeException("Failed to load properties", e);
}
finally {
  try {
    in.close();
  } catch (IOException e) {
    // don't care
  }
}

No comments:

Post a Comment

Note: Only a member of this blog may post a comment.