I am developing a JSF Web Application, which is a control panel to change 8 Parameters. As I don't want to create a database for only 8 params I wanted to store them in a properties file. I am already able to read them from my properties file but i fail writing them back. Here is my code.
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;
import com.sun.javafx.fxml.PropertyNotFoundException;
public class PropertyAccess {
private static final String DEFAULT_PROP_FILE = "params.properties";
private String propFileName;
private Properties props;
public PropertyAccess() {
this.propFileName = DEFAULT_PROP_FILE;
}
public PropertyAccess(String propFileName) {
this.propFileName = propFileName;
}
public String getProperty(String propertyKey) {
props = new Properties();
InputStream in = getClass().getClassLoader().getResourceAsStream(propFileName);
try {
if (in != null) {
props.load(in);
in.close();
} else {
throw new FileNotFoundException("property file '" + propFileName + "' not found in the classpath");
}
} catch (IOException e) {
e.printStackTrace();
}
String result = props.getProperty(propertyKey);
if (result==null){
throw new PropertyNotFoundException("Property '" + propertyKey + "' not found in '" + propFileName + "'");
}
return result;
}
public void setProperty(String propertyKey, String propertyValue){
try {
props = new Properties();
props.setProperty(propertyKey, propertyValue);
FileOutputStream out = new FileOutputStream(propFileName);
props.store(out, null);
out.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
That is my property access class. But writing the properties does not work:
PropertyAccess pa = new PropertyAccess();
pa.setProperty("test", "testvalue");
pa.getProperty("test");
throws an Exception that the property wasnt found.
Any Ideas?