Java 使用表单值更新属性文件值
我有一个jsp文件,在其中加载属性文件中的现有值。当用户编辑现有值并提交表单时,必须使用该值更新属性文件。有人能帮我吗?我只使用javaJava 使用表单值更新属性文件值,java,Java,我有一个jsp文件,在其中加载属性文件中的现有值。当用户编辑现有值并提交表单时,必须使用该值更新属性文件。有人能帮我吗?我只使用java FileInputStream in = new FileInputStream("Example.properties"); Properties props = new Properties(); props.load(in); 现在更新它 FileOutputStream outputStream = new FileOutputStream("Exa
FileInputStream in = new FileInputStream("Example.properties");
Properties props = new Properties();
props.load(in);
现在更新它
FileOutputStream outputStream = new FileOutputStream("Example.properties");
props.setProperty("valueTobeUpdate", "new Value");
props.store(outputStream , null);
outputStream .close();
实现相同目标的另一种方法在
以下是一个如何更新属性文件的示例:
public class PropertyManager {
private static Properties prop = new Properties();
private static String PROPERTY_FILENAME = "config.properties";
public static void main(String[] args) {
loadProperty();
System.out.println(prop.get("myProperty"));
updateProperty("myProperty", "aSecondValue");
}
public static void loadProperty(){
InputStream input = null;
try {
input = new FileInputStream(PROPERTY_FILENAME);
// load a properties file
prop.load(input);
} catch (IOException ex) {
ex.printStackTrace();
} finally {
if (input != null) {
try {
input.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
public static void updateProperty(String name, String value){
OutputStream output = null;
try {
output = new FileOutputStream(PROPERTY_FILENAME);
// set the properties value
prop.setProperty(name, value);
// save properties to project root folder
prop.store(output, null);
} catch (IOException io) {
io.printStackTrace();
} finally {
if (output != null) {
try {
output.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
我允许您通过检索的方式更改“新属性”。我编辑了我的答案以编写一个完整的示例,并且文件已正确更新。希望这有助于代码正常工作。但是更改将存储在项目中的新属性文件中。但我希望这些更改反映在src文件夹中的现有属性文件中
PropertiesConfiguration config = new PropertiesConfiguration("/Users/abc/Documents/config.properties");
config.setProperty("Name", "abcd");
config.setProperty("Email", "abcd@gmail.com");
config.setProperty("Phone", "123456");
config.save();