You’ll often want to configure parameters in a properties file and read this into a class.

config.properties:
value.a=orange
value.b=apple

If you’re simply loading a file in a java program you can use:

Properties props = new Properties();
props.load(new FileInputStream("config.properties"));
String value = props.getProperty("value.a");

But when loading a property file in a web application you should package the file in your deployed archive and load the file from the classpath.  This avoids problems with loading files from different locations on a file system.

build.xml: gen-jar-files target






This takes any properties files in the resources.dir and copies them into the jar file.  Now you can access the file within your application from the classpath:

ClassLoader cl = this.getClass().getClassLoader();
InputStream is = cl.getResourceAsStream("config.properties");
Properties configProperties  = new Properties();
try {
configProperties.load(is);
String valueA = configProperties.getProperty("value.a");
} catch (IOException e) {
e.printStackTrace();
}

%d bloggers like this: