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
- Close the reader after you are done with reading i.e. after reading properties.
- Catch exceptions and treat them with due importance. If it is initial configuration file of application leading to FileNotFoundException then take it to fatal level.
- Cache the properties appropriately so that you do not load them at every access.
- If required, provide a mechanism to reload the properties.
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
}
}
}
}
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.
