Using Property files in Java

Creating configuration files in Java is simple and straightforward. We just have to use the Properties object. The example of a property file is here below:

filename: config.properties ( or you can just create any file name you want, but better follow convention )
content: example.property=skeep

Here is a sample code to get the “skeep” String , which is defined in “example.property”

– Define Properties object and InputStream object. Properties can process a “key=property” content, while InputStream is for file reading.
– Define the property file location. In this example, we just use the relative path of the project. Therefore file name and path should be included.
– Use FileInputSteam() constructor to read the property file, then use the getProperty() method to retrieve the property content of a key.
– It is proper to use a close input stream in a finally block, in case file access will fail.
– Properties class can also read integers.
– We can add more “key-property” values in the properties file.

Properties prop = new Properties();
InputStream input = null;
 try{
  input = new FileInputStream("config.properties");
  prop.load(input);
  sensitive_words = prop.getProperty("example.property");
 } finally {
   if (input != null) {
    try {
      input.close();
    } catch (IOException e) {
      e.printStackTrace();
    }
   }
 }
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s