2017-09-15 86 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();