2017-09-15 92 views
1

使用值注释读我有一个属性文件说如下:更新值在春季

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 
+1

[在运行时与@Value注释更新场]的可能的复制(https://stackoverflow.com/questions/16478679/update-field-annotated-with-value-in-runtime) –

回答

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();