0

有没有办法用 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 字段。

4

2 回答 2

1

尝试

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

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

于 2012-07-31T03:32:42.037 回答
-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());
于 2012-07-31T05:32:04.213 回答