Sheila's Blog

Software Development

Sheila's Blog header image 2

Loading a properties file in a java web app

March 31st, 2009 by Sheila

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 <copy todir="${jar.dir}"> <fileset dir="${resources.dir}"> <include name="*.properties" /> </fileset> </copy>

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(); }

Tags:   · No Comments

Leave a Comment

0 responses so far ↓

There are no comments yet...Kick things off by filling out the form below.