Read A Property File in Java 6

Almost all applications are reading something from the file system. All of them have some kind of properties stored outside the application Java code, so that it can be changed without having to recompile entire code. These properties can be initial configuration properties, database connection properties, or even exception messages. You can find many ‘.properties’ files in any application classpath. Here is a code snippet that can be used to read these property files. Here are the points to remember

Notice the FileReader we are using. You can have xml files as property files. But you will have to use correct file reader.

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

public class ReadPropertyFile {

	public static void main(String[] args) {
		ReadPropertyFile readPropFile = new ReadPropertyFile();
		readPropFile.readProperties();
	}

	public void readProperties(){
		FileReader fileReader = null;
		try{
			Properties props = new Properties();
			fileReader = new FileReader("C:\\PropertyExample.properties");
			props.load(fileReader);
			System.out.println("Read Successful: " + props.toString());
		}catch(FileNotFoundException fnfe){
			fnfe.printStackTrace();
		}catch(IOException ioe){
			ioe.printStackTrace();
		}finally{
			try{
				fileReader.close();
			}catch(IOException ioe1){
				//Leave it
			}
		}
	}
}
  • Share/Bookmark
Java

If you enjoyed this post, please consider to leave a comment or subscribe to the feed and get future articles delivered to your feed reader.

Leave Comment

(required)

(required)