儘管java.util.properties允許讀取和寫入屬性文件,但寫入不會保留格式。這並不奇怪,因爲它沒有綁定到屬性文件。更好的類來更新屬性文件?
是否有一個PropertyFile類在那裏 - 或者這樣 - 保留註釋和空白行並更新屬性值到位?
儘管java.util.properties允許讀取和寫入屬性文件,但寫入不會保留格式。這並不奇怪,因爲它沒有綁定到屬性文件。更好的類來更新屬性文件?
是否有一個PropertyFile類在那裏 - 或者這樣 - 保留註釋和空白行並更新屬性值到位?
它沒有比Apache的Commons Configuration API好多了。這提供了從屬性文件,XML,JNDI,JDBC數據源等進行配置的統一方法。
它處理屬性文件非常好。它允許您從屬性中生成一個PropertiesConfigurationLayout對象,該對象儘可能多地保留有關您的屬性文件的信息(空格,註釋等)。當您保存對屬性文件的更改時,這些將盡可能保留。
樣品的編號:
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.InputStreamReader;
import org.apache.commons.configuration.ConfigurationException;
import org.apache.commons.configuration.PropertiesConfiguration;
import org.apache.commons.configuration.PropertiesConfigurationLayout;
public class PropertiesReader {
public static void main(String args[]) throws ConfigurationException, FileNotFoundException {
File file = new File(args[0] + ".properties");
PropertiesConfiguration config = new PropertiesConfiguration();
PropertiesConfigurationLayout layout = new PropertiesConfigurationLayout(config);
layout.load(new InputStreamReader(new FileInputStream(file)));
config.setProperty("test", "testValue");
layout.save(new FileWriter("path\\to\\properties\\file.properties", false));
}
}
參見:
您可以看看Apache Commons Configuration,其中包含PropertiesConfiguration類。 不過,我從來沒有使用過,我不知道,如果它保留的意見和格式...
然而,worthes一試...
根據文檔,「PropertiesConfigurationLayout」類將保留格式和註釋。 – 2009-02-19 16:02:32
我曾經看到一個類來做到這一點與INI文件,但無法找到鏈接了。如果你找不到其他東西,你可以試試DecentXML。我爲這個XML解析器編寫了特定的設計目標,以保持原始格式爲100%(即註釋,元素中的怪異空間或根元素周圍的所有內容)。
在解析生成的XML文檔的過程中,您只需記住包含選項值的元素並替換其中的文本節點。當你保存時,沒有任何未修改的內容會以任何方式改變。
用於使用Apache共享配置librar示例代碼由Patrick Boos貢獻是不必要的複雜。除非需要對輸出進行高級控制,否則不需要明確使用PropertiesConfigurationLayout。 PropertiesConfiguration本身就足以保護意見和格式:
PropertiesConfiguration config = new PropertiesConfiguration("myprops.properties");
config.setProperty("Foo", "Bar");
config.save();
(注:此代碼適用於現有的1.10穩定版我沒有檢查它是否工作在2.0阿爾法建立當前可用)
File file = new File("src/test/resources/1automation.properties");
PropertiesConfiguration config = new PropertiesConfiguration();
PropertiesConfigurationLayout layout = new PropertiesConfigurationLayout(config);
layout.load(new InputStreamReader(new FileInputStream(file)));
FileWriter fw = new FileWriter("src/test/resources/1automation.properties",false);
config.setProperty("myssi.admin.name", "testValue");
layout.save(fw);
這很好,並保留評論。冒昧添加一些示例代碼:) – 2015-01-06 14:40:09
提供的代碼不編譯.. propsFile未聲明 – blank 2015-04-09 13:02:42
如果您有一個鍵值,如Spring.Names = cookie @!jar @!johnson @!james @!green @!帕特里克。你會在帕特里克之後加上「吉米」嗎? – Jesse 2016-12-12 18:50:50