【问题标题】:Updating property value in properties file without deleting other values [duplicate]更新属性文件中的属性值而不删除其他值[重复]
【发布时间】:2013-02-26 13:26:34
【问题描述】:

First.properties的内容:

name=elango
country=india
phone=12345

我想将 countryindia 更改为 america。这是我的代码:

import java.io.*;
public class UpdateProperty 
{
    public static void main(String args[]) throws Exception 
    {   
        FileOutputStream out = new FileOutputStream("First.properties");
        FileInputStream in = new FileInputStream("First.properties");
        Properties props = new Properties();
        props.load(in);
        in.close();
        props.setProperty("country", "america");
        props.store(out, null);
        out.close();
    } 
}

First.properties的输出内容:

country=america

其他属性被删除。我想更新一个特定的属性值,而不删除其他属性。

【问题讨论】:

标签: java properties


【解决方案1】:

关闭输入流后打开输出流并存储属性。

FileInputStream in = new FileInputStream("First.properties");
Properties props = new Properties();
props.load(in);
in.close();

FileOutputStream out = new FileOutputStream("First.properties");
props.setProperty("country", "america");
props.store(out, null);
out.close();

【讨论】:

  • 感谢 Vasyl Keretsman 我更改了代码。这是正确的吗?属性 props = new Properties();道具.load(in); props.setProperty("国家", "美国"); props.store(out, null); out.close();附寄();但答案是一样的。我没有得到预期的答案
  • 不正确。我已将代码添加到我的答案中
  • 谢谢 Vasyl Keretsman。它正在工作..
  • @VasylKeretsman 它已删除文件中所有现有的 cmets
  • 这如何成为公认的答案?它会删除所有以前设置的属性。
【解决方案2】:
Properties prop = new Properties();
prop.load(...); // FileInputStream 
prop.setProperty("key", "value");
prop.store(...); // FileOutputStream 

【讨论】:

    【解决方案3】:

    您可以使用Apache Commons Configuration 库。 最好的部分是,它甚至不会弄乱属性文件并保持原样 (even comments)。

    Javadoc

    PropertiesConfiguration conf = new PropertiesConfiguration("propFile.properties");
    conf.setProperty("key", "value");
    conf.save();    
    

    【讨论】:

    • 这比接受的答案要好得多
    • @José Mª 我下载了commons.apache.org/proper/commons-configuration/index.html ApacheCommons Configurator 2.1.1,似乎save() 方法和其他一些方法不存在。有没有其他选择?
    • @GOXR3PLUS 抱歉,我现在无法对其进行测试,但我认为它应该可以工作,因为网站标题处有一个注释,您可以在其中看到:“上次发布时间:2017 年 2 月 8 日|版本:2.1.1" 这很令人困惑,但您仍然可以使用旧版本。不幸的是,我不能再帮你了:(
    • @JoséMª 我使用的是 1.1 版本。此外,2.1 版本中包含 save() 方法。 commons.apache.org/proper/commons-configuration/apidocs/org/…
    • 嗨@J.Doem:您可以使用旧的1.10 version,它有一个String args 构造函数来直接传递文件名。否则,对于 V2,您可以使用 PropertyConfiguration 类的 loadIncludeFile(String fileName) 方法来传递文件名。
    猜你喜欢
    • 1970-01-01
    • 2021-11-23
    • 1970-01-01
    • 1970-01-01
    • 2022-01-21
    • 2015-08-28
    • 1970-01-01
    • 2021-11-21
    • 1970-01-01
    相关资源
    最近更新 更多