簡體   English   中英

設置屬性,並將它們存儲在文件中

[英]Setting properties, and storing them in a file

我有一個類,它從包中處理給定的“配置文件”。 由於我只需要處理簡單的鍵/值對,我認為使用Properties會沒問題。

import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;

public class ConfigFile {

    private Properties appProps = new Properties();
    private String filename;
    private InputStream in;

    public ConfigFile(String file) throws FileNotFoundException, IOException {
        this.filename = file;
        in = getClass().getResourceAsStream(this.filename);
        appProps.load(in);
        in.close();
    }

    public String getProp(String key) {
        return appProps.getProperty(key);
    }

}

現在,我想創建一個setProp(String key, String value)方法,它顯然設置了給定的屬性,並將其保存到它讀取的同一個文件中。 我似乎無法弄清楚如何做到這一點。 我想我需要調用appProps.setProperty(key, value) ,然后使用OutputStream做一些魔術,但我堅持認為。 任何幫助,將不勝感激!

        Properties prop = new Properties();

    try (FileOutputStream os = new FileOutputStream("config.properties"))
    {
        //set the properties value
        prop.setProperty("database", "localhost");
        prop.setProperty("dbuser", "mkyong");
        prop.setProperty("dbpassword", "password");

        //save properties to project root folder
        prop.store(os, null);

    } catch (IOException ex) {
        ex.printStackTrace();
    }

這應該解釋一切,如果不隨意問。

自動保存的此類功能不直接在Properties類中提供,但您可以組合現有功能。 您必須自己實現此組合,方法是通過子類化Properties並實現新方法或添加實用程序方法。 如果您對現有屬性不感興趣,可以編寫如下代碼:

void update(String file, String key, String value) throws IOException {
    Properties properties = new Properties();
    InputStream is = new FileInputStream(new File(file));
    try {
    properties.load(is);
    } finally {
      is.close();
    }
    properties.setProperty(key, value);
    OutputStream os = new FileOutputStream(new File(file));
    try {
      properties.store(os);
    } finally {
      os.close();
    }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM