Simple Properties Files and Null Check

When performing a get on the properties from a property file, 

  1. If the property is entered, but the value is blank. e.g. file contains ‘field=’
    properties.get() returns ”
  2. If the property and its value is entered. e.g. file contains ‘field=value’
    properties.get() returns ‘value’
  3. If the property is not entered into the property file
    properties.get() will return null.

Lets the following code to demonstrate what I said just now.

Tokenizer.java

class Tokenizer { 
    public static void main(String args[]) { 

          Properties properties = new Properties(); 
          try { 
              properties.load(new FileInputStream(“path/filename”)); 
          } catch(IOException e) { 
              e.printStackTrace(); 
              System.exit(1);  
          } 

          StringTokenizer tokenizer = new StringTokenizer(properties.get(“testInput”, “,”));  
          while(tokenizer.hasMoreTokens()) { 
              System.out.println(tokenizer.nextToken()); 
          }  
      } 
   } 
}

Run the java file with properties.properties without testInput.

This would result in a NullPointerException  However, putting “testInput=” or “testInput=value” will not result in a NullPointerException. Do ponder over it for a second. And you’ll realize how important the null pointer check is here.

Advertisements

About Gaurav

I'm Gaurav; friends call me Teddy, n i'm shivi fr my family!! A java enthusiast who likes experimenting with what he knows. View all posts by Gaurav

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

%d bloggers like this: