覆盖属性文件

时间:2012-07-31 03:30:58

标签: java properties

有没有办法用Java覆盖属性文件中的一个字段?

例如,如果我的app.properties看起来像

dbpassword=password
database=localhost
dbuser=user1

我希望将其更改为

dbpassword=password
database=localhost
dbuser=user2

只有一个setProperty命令,即无需覆盖我的其他字段,我可以这样做吗?我尝试了以下方法:

prop.setProperty("dbuser", "user2");

prop.store(new FileOutputStream("app.properties",true), null);

但它只是将属性附加到文件中,并且不会覆盖现有的dbuser字段。

2 个答案:

答案 0 :(得分:1)

尝试

prop.store(new FileOutputStream("app.properties",false), null);

相反。基本上你要求FileOutputStream将结果附加到现有文件,而不是覆盖它

答案 1 :(得分:-1)

The  example, PropertiesTest, creates a Properties object and initializes it from myProperties.txt .

subliminal.message = Buy StayPuft Marshmallows!
PropertiesTest then uses System.setProperties to install the new Properties objects as the current set of system properties.


import java.io.FileInputStream;
import java.util.Properties;

public class PropertiesTest {
    public static void main(String[] args)
        throws Exception {

        // set up new properties object
        // from file "myProperties.txt"

        Properties p =
            new Properties(System.getProperties());
        p.load(propFile);

        // set the system properties
        System.setProperties(p);
        // display new properties
        System.getProperties().list(System.out);
    }
}
Note how PropertiesTest creates the Properties object, p, which is used as the argument to setProperties:

Properties p = new Properties(System.getProperties());