2015-03-02 35 views

回答

0

這裏介紹的另一種方式是如何更新你的屬性文件示例:

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

     } 
    } 

我讓你改變「新的屬性」,通過你檢索它的方式。

+0

我試過這段代碼,屬性文件沒有得到更新。 – 2015-03-02 11:58:03

+0

我編輯我的答案編寫完整的示例,並正確更新文件。希望得到這個幫助 – vincent 2015-03-02 12:42:01

+0

代碼工作正常。但是所做的更改將存儲在項目中的新屬性文件中。但我希望所做的更改反映在src文件夾內的現有屬性文件中 – 2015-03-03 06:36:16

0
PropertiesConfiguration config = new PropertiesConfiguration("/Users/abc/Documents/config.properties"); 
     config.setProperty("Name", "abcd"); 
     config.setProperty("Email", "[email protected]"); 
     config.setProperty("Phone", "123456"); 
     config.save();