Using properties file in Java

Posted on 15-03-2013 08:33 by graham
It is a good practice to keep all configuration of your system in an external properties file, not in the code itself. This allows your application to be more configurable and allows you to introduce changes to the configuration without recompiling the code.

Properties file format


Java property files contain properties as key-value pair separates by an equals symbol.
setting.properties
myapp.url=mydomain.com
myapp.name=My Application

Reading properties from file


Properties can be parsed using the java.util.Properties class:
Properties properties;
properties.load(PropertyUtil.class.getClassLoader().getResourceAsStream("settings.properties"));

Utility class for accessing properties


Using the code above we can build a nice utility class that will handle property loading for us.
PropertyUtil.java
public class PropertyUtil
{
private static Properties properties;

public static String getProperty(String name) throws OrgStatsException
{
if (properties == null)
{
properties = new Properties();
try
{
properties.load(PropertyUtil.class.getClassLoader().getResourceAsStream("config.properties"));
}
catch (Exception e)
{
throw new PropertyUtilException("Could not load config.properties file: " + e.getMessage());
}
}
return properties.getProperty(name);
}
}
Comments

 

Add comment

Has this tutorial been helpful to you? Or do you see anything wrong? We appreciate your opinion!
Your comment:
Show formatting hints
HTML is disallowed, but in your text you can use the following markup
  • [code][/code] for a block of code
  • [tt][/tt] for inline code
  • [link]link href|link anchor[/link] for links
  • [b][/b] for bold text
Email:
+ Ask a question
If you have a technical question related to programming and computers, ask it here. Other users will help you solve it!
Unanswered questions
Share your knowledge by helping others solve their problems