我正在开发一个JSF Web应用程序,它是一个用于更改8个参数的控制面板。由于我不想仅为8个参数创建数据库,我想将它们存储在属性文件中。我已经能够从我的属性文件中读取它们,但我没有写回来。这是我的代码。
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();
}
}
}
这是我的属性访问类。但是编写属性不起作用:
PropertyAccess pa = new PropertyAccess();
pa.setProperty("test", "testvalue");
pa.getProperty("test");
抛出异常,找不到该属性。
任何想法?