17 January 2011

Reading property file in java

Reads a property list (key and element pairs) from the input stream. The stream is assumed to be using the ISO 8859-1 character encoding; that is each byte is one Latin1 character. Characters not in Latin1, and certain special characters, can be represented in keys and elements using escape sequences similar to those used for character and string literals. The differences from the character escape sequences used for characters and strings are:
  • Octal escapes are not recognized.
  • The character sequence \b does not represent a backspace character.
  • The method does not treat a backslash character, \, before a non-valid escape character as an error; the backslash is silently dropped. For example, in a Java string the sequence "\z" would cause a compile time error. In contrast, this method silently drops the backslash. Therefore, this method treats the two character sequence "\b" as equivalent to the single character 'b'.
  • Escapes are not necessary for single and double quotes; however, by the rule above, single and double quote characters preceded by a backslash still yield single and double quote characters, respectively.
An IllegalArgumentException is thrown if a malformed Unicode escape appears in the input.

Java API : java.utils.Properties

Reading properties from Property file:

1. Load the property file

Properties props = new Properties();
try {
       props.load(new FileInputStream("property file path"));
} catch (Exception e) {
    e.printStackTrace();
}


2. Getting properties
String valueForProp = props.getProperty("attribute");



3. Sample property file:
# This is sample attribute comment attr1 = value1

# Attribute having multiple line string
attr2 = this is multi line \
             value for attribute attr2


! you can add comment like this or
# like this

No comments:

Post a Comment