Monday, December 29, 2008

Reading A Properties File In Java

How to read a properties file in Java?
Well, here I explain a simple way to read a properties file in Java.

Here is what I have done :
1) I created a folder named 'tests'. Inside this folder I created 2 files.
2) The First file 'PropertyReader.java' will contain the Java source code to read the data from a properties file.
3) The second file named 'SomeProps.properties' is the properties file that needs to be read.

Following are the contents of these two files:

SomeProps.java
name=ryan
interest=programming


PropertyReader.java

//----------Source Code Begins Here------------------------
import java.util.Properties;
import java.io.FileInputStream;
import java.io.IOException;

public class PropertyReader
{
public static void main(String[] args) throws IOException
{
Properties p=new Properties();
p.load(new FileInputStream("SomeProps.properties"));
System.out.println(p.getProperty("name"));
System.out.println(p.getProperty("interest"));
}
}
//-------------------Source Code Ends Here----------------------

The code hardly needs any explanation. All it does is read a properties file using a FileInputStream object and then loading the values into the properties object using the load() method.

Happy programming ;)

Signing Off
Ryan

No comments: