Friday, January 29, 2016

Properties file Read/Write in Java

protected static Properties prop;
/**
* Method to load Property files
*
* @param filePath
* @return Properties
* @throws Exception
*/
public static Properties loadProperties(String filePath) throws Exception {
try {
prop = new Properties();
// Read object repository file
FileInputStream fis = new FileInputStream(new File(filePath));

// load all objects
prop.load(fis);
return prop;
} catch (Exception e) {
e.printStackTrace();;
}
return prop;

}

/**
* Method to get property valueF
*
* @param p
* -Properties
* @param name
* @return propValue
*/
public static String getProperties(Properties p, String name) {
String propValue = null;
try {
propValue = p.getProperty(name);
return propValue;
} catch (Exception e) {
e.printStackTrace();
}
return propValue;
}
 
/**
     * To set value into Property file
     *
     * @param prop
     * @param key
     * @param value
     */
    public void setProperty(Properties prop, String key, String value, String filePath) throws Exception {
        try {
            prop.setProperty(key, value);
            prop.store(new FileOutputStream(filePath), null);
        } catch (Exception e) {
          e.printStackTrace();
        }
    }
 
/**
     * Loading A Property File From The Classpath
     *
     * @param fileName
     *            - only file name without complete path
     * @throws Exception
     */
    public Properties loadPropertyFileFromClasspath(String fileName) throws Exception {
        try {
            if (fileName != null && !fileName.isEmpty()) {
                InputStream ins =  this.getClass().getClassLoader().getResourceAsStream(fileName);
                prop.load(ins);
            } else {
                throw new Exception("property file '" + fileName + "' not found in the classpath");
            }
        } catch (Exception e) {
            throw new Exception("Error while loadProperties: " + e.toString());
        }
        return prop;

    }

No comments:

Post a Comment