Handling properties file using Java
August 17, 2010 1 Comment
Handling properties file using Java
Introduction:
Properties are configuration values managed as key/value pairs. In each pair, the key and value are both String values. The key identifies, and is used to retrieve, the value, much as a variable name is used to retrieve the variable’s value. For example, a Client Server application should communicate with each other,so the Server information has to be stored in Client in order to establish the communication with the Server. The server information like IP Address can be stored and retrieved from the Properties file.
Basics on Handling Properties file:
The following procedures has to be followed in order to write Properties to Properties file.
- Create instance of Properties file.
- Create instance of FileOutput Stream Class
- Set the property Values using setProperties method ( Click here to view more on setProperties )
- Store the properties into file using store method.
- Close the Output Stream Object
The following procedures has to be followed in order to Read Properties from Properties file.
- Create instance of Properties file.
- Load the FileInput Stream Object
- Read the Value using the Key value. ( using getProperties method )
- Close the Input Stream Object
Click here to see more details on Properties class.
Example:
The following example shows how to Write Properties into Properties file.
/* PropTest.java by elangovan */ import java.util.*; import java.io.*; class PropTest { public static void main(String args[]) throws IOException { if( args.length < 2) { System.out.println("Usage: PropTest <UserName> <FavColor>"); System.exit(0); } Properties prop=new Properties(); FileOutputStream out=new FileOutputStream(new File("UserSetting.ini")); prop.setProperty("UserName",args[0]); prop.setProperty("FavColor",args[1]); prop.store(out,""); out.close(); } }
Running the program
javac PropTest.java java PropTest MyName Blue
The following example shows how to Read from Properties file.
/* PropTest.java by elangovan */ import java.util.*; import java.io.*; class PropReadTest { public static void main(String args[]) throws IOException { String UserName="",FavColor=""; Properties prop=new Properties(); FileInputStream fin=new FileInputStream(new File("UserSetting.ini")); prop.load(fin); UserName = prop.getProperty("UserName"); FavColor = prop.getProperty("FavColor"); fin.close(); System.out.println("User name is:"+UserName); System.out.println("Favourte Color is:"+FavColor); } }
Running the program
javac PropReadTest.java java PropReadTest
Nice post , thanks for sharing information keep it up.
Javin
Why String is immutable in Java
FIX Protocol tutorial