Wednesday, May 5, 2010

Read value from Java properties

Here, you will find the source code to read value of the key from properties file. java.util.Properties class extends Hashtable. Properties class creates the properties file which stores key - value pair using Hashtable. To retrieve value from properties file we have to follow following steps.
  1. Create an object of Properties class.
  2. Load properties file using FileInputStream into properties object.
  3. Get value from properties object using getProperty() method passing key as an input.
The below code will help to understand more...

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.Properties;

public class PropertiesReadTest {

    public static void main(String[] args) {
        Properties properties = new Properties();
        try {
            properties.load(new FileInputStream("C:\\temp\\test.properties"));
            String value = properties.getProperty("key");
            System.out.println("Value = " + value);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

Output is shown here in following image





3 comments:

  1. Very useful article...My understanding is that if there is a goal

    read something from file
    write something to a file

    to achieve this you use any programming language or scripting language it is same, the only difference is how you implement it and take it further

    ReplyDelete
  2. Yes, It is right we can choose any language for reading and writing content from file. But in this case reading java properties files is normal practice but in this case output is in the form of key and value pair.

    ReplyDelete
  3. Hi

    I read this post 2 times. It is very useful.

    Pls try to keep posting.

    Let me show other source that may be good for community.

    Source: Property interview questions

    Best regards
    Jonathan.

    ReplyDelete