Properties class

Properties class:

Proprties is a child class of a Hashtable.

The Properties class represents a persistent set of properties.

The Properties can be saved in to a File.we can load Properties file into our java program.

In the Properties class both key and value are in the form of Strings.

The Proerties class implements serializable and cloneable interfaces.

Advantage:

The main advantage of this approach is if anything change in the properties file Just Redployment is enough.

Constructors:

Properties p = new Properties();

Methods available in Properties class:

public String getProperty(String Key)

This mehod returns value associated with the specified key.The method returns null if the property is not found.

public String getProperty(String key ,String defaultValue)

This method Searches for the property with the specified key in this property list. If the key is not found in this property list, the default property list, and its defaults, recursively, are then checked. The method returns the default value argument if the property is not found.

public Enumeration propertyNames()

Returns an enumeration of all the keys in this property list, including distinct keys in the default property list if a key of the same name has not already been found from the main properties list.

public void load(InputStream inStream)throws IOException:

This method is used to load properties from properties files into java properties object.

Note:

Here I have created one filename called data.properties like the following and iam readin properties values into java application.


Username = ABCD
Password = 1234


Example:


package com.javalschool;

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

public class PropertiesDemo {

/**
* @param args
* @throws IOException
*/
public static void main(String[] args) throws IOException {
Properties p = new Properties();
FileInputStream fis = new FileInputStream("data.properties");
p.load(fis);
System.out.println(p);

}

}



OutPut:


{Username=ABCD, Password=1234}



No comments:

Post a Comment