Reading properties file in Java is much easier than you might have thought. Following example illustrates one simple way of reading properties from a properties file.

Let’s say we need to read from myConfig.properties file.




The properties file has following entries.

Directory = C:/prodFiles/
NumberOfFiles = 25
Extension = java

Here is the java code to read the values of these keys.

import java.util.Properties;
import java.io.*;
public class ReadValues{
   private static final String PROP_FILE="myConfig.properties";
   public void readPropertiesFile(){
       try{
  	     InputStream is = ReadValues.class.getResourceAsStream(PROP_FILE);
	     Properties prop = new Properties();
             prop.load(is);
	     String directory = prop.getProperty("Directory");
             String numberOfFiles = prop.getProperty("NumberOfFiles");
	     String  fileExtension = prop.getProperty("Extension");
             is.close();
	  /* code to use values read from the file*/
       }catch(Exception e){
         System.out.println("Failed to read from " + PROP_FILE + " file.");
       }
   }
  }

The code is quite simple and self explanatory. Let me know if you have any questions.

If you enjoyed this post, make sure you subscribe to my RSS feed!
article clipper vert How to read properties file in Java.
 

Related posts: