Monday, August 13, 2012

FAQ in Java/J2EE updated daily

Recently one of my colleague had problems loading values from a property file.He analyzed the problem and emphasized that having spaces in the key is creating problems.We have to remove all the spaces in the properties file keys to satisfy him.The problem persisted..

Based on this I would like to provide some basic theory and Q and A on Properties.

1) How to load properties files in Java?.

    Option 1: We can load using absolute file paths or relative file paths.Using absolute file paths is not portable and relative files are resolved based on the JVM directory which users might have control in production.We normally should not use files API to access resources to be platform independent.

   Option 2: Using a property file as a classpath resource.Recommended way to load a resource and is portable.

2) Can we have default values for the properties in java?.

     From the API 'A property list can contain another property list as its "defaults"; this second property list is searched if the property key is not found in the original property list'.So yes but using java API and not in the file.

Properties(Properties defaults) 
          Creates an empty property list with the specified defaults.

or

getProperty(String key, String defaultValue) 
          Searches for the property with the specified key in this property list.


3) Can we use Unicode characters in properties files?

      No,in properties the input/output stream is encoded in ISO 8859-1 character encoding.

4) How can we read Unicode data from properties file?.

      Characters that cannot be directly represented in this encoding can be written using Unicode escapes only a single 'u' character is allowed in an escape sequence. The native2ascii tool can be used to convert property files to and from other character encodings.(From the API).


In Java 1.6 you can use other encodings by using the methods that use Reader/Writer instead of InputStream/OutputStream

Sample: In Java 1.6

Properties props = new Properties();
URL resource = getClass().getClassLoader().getResource("data.properties");         
props.load(new InputStreamReader(resource.openStream(), "UTF8"));




5) How to read properties from properties in java?.

     Use any of the method to get the stream

     ClassLoader.getResourceAsStream ("some/pkg/resource.properties");
     Class.getResourceAsStream ("/some/pkg/resource.properties");
     ResourceBundle.getBundle ("some.pkg.resource");


   
Method
Parameter format
Lookup failure behavior
Usage example
ClassLoader.
getResourceAsStream()
"/"-separated names; no leading "/" (all names are absolute)
Silent (returns null)
this.getClass().getClassLoader()
.getResourceAsStream
("some/pkg/resource.properties")
Class.
getResourceAsStream()
"/"-separated names; leading "/" indicates absolute names; all other names are relative to the class's package
Silent (returns null)
this.getClass()
.getResourceAsStream
("resource.properties")
ResourceBundle.
getBundle()
"."-separated names; all names are absolute;.properties suffix is implied
Throws unchecked
java.util.MissingResourceException
ResourceBundle.getBundle
("some.pkg.resource")
   
     after retrieving the input stream we can load the same into a property object using

     Properties prop = new Properties();
     prop.load(inputStream);

6) Are leading and training spaces considered part of the key in properties?.

     No, from the API Any white space after the key is skipped; if the first non-white space character after the key is '=' or ':', then it is ignored and any white space characters after it are also skipped.

Example : As an example, each of the following three lines specifies the key "Truth" and the associated element value "Beauty"
Truth = Beauty
        Truth:Beauty
 Truth                  :Beauty

7) Can I have only a key in property file without the value?.
     Yes,and the value will be an empty string by default.

8) Can I load properties from an XML file?.

      Yes,we can load an XML file using the method,By default the UTF-8 characterencoding is used,however a specific encoding may be specified if required.
 public void loadFromXML(InputStream in)

 and the DTD should be of the following format

 <?xml version="1.0" encoding="UTF-8"?>
 <!-- DTD for properties -->

 <!ELEMENT properties ( comment?, entry* ) >

 <!ATTLIST properties version CDATA #FIXED "1.0">

 <!ELEMENT comment (#PCDATA) >

 <!ELEMENT entry (#PCDATA) >

 <!ATTLIST entry key CDATA #REQUIRED>

9) Can we save a modified properties to the file?.
     Yes, using store or storeToXML.

10) Is the Properties class thread-safe,can multiple threads access the properties safety?.

     Yes. (From the API: This class is thread-safe: multiple threads can share a single Properties object without the need for external synchronization)

11) What is the super class of Properties?.

    HashTable.

12) Is Properties Serializable or Cloneable?.
    Both.

No comments:

Post a Comment