我有一个属性文件,如下所示:
apple=1
mango=2
banana=3
pineapple=4
我在java程序中使用值注释来访问值。我在我的类中有一个方法,它计算一个值,我想用属性文件中的apple属性更新该方法返回的值。
public class test {
@Value("${apple}")
private int apple;
public void testMethod() {
int new_val = 0;
if (apple > 0)
new_val = 300;
else
new_val = 200;
// now i want to update the value of apple in the file to new_val,(apple = new_val) other attributes should remain unchanged.
}
}
有人可以告诉我如何更新属性文件中的值。在这个例子中,我希望我的属性文件成为
apple=300
mango=2
banana=3
pineapple=4
答案 0 :(得分:1)
通常我们在属性中定义常量值,因此它不会改变。 但如果您需要更改它。
你可以这样做:
1)使用Apache Commons Configuration library
PropertiesConfiguration conf = new PropertiesConfiguration("yourproperty.properties");
props.setProperty("apple", "300");
conf.save();
2)使用Java输入和输出流
FileInputStream in = new FileInputStream("yourproperty.properties");
Properties props = new Properties();
props.load(in);
in.close();
FileOutputStream out = new FileOutputStream("yourproperty.properties");
props.setProperty("apple", "300");
props.store(out, null);
out.close();