2012-07-31 81 views
0

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

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

dbpassword=password 
database=localhost 
dbuser=user1 

,我想它只有一个的setProperty命令,即改为

dbpassword=password 
database=localhost 
dbuser=user2 

,而无需重写我的其他领域,可我这么做?我尝试了以下方法:

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

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

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

+0

那么,如果你只是想再次从属性文件中读取...这最终将工作;如在附加文件中将使用最后一个值。话虽如此,我相信这不是你想要达到的。你想保护数据吗? – SiB 2012-07-31 04:27:23

回答

1

尝试

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

相反。基本上你问的FileOutputStream追加的结果,现有的文件,而不是覆盖它

+0

如果我这样做,其他字段将消失,因为属性文件将被覆盖,现在只有一个属性在写入文件之前正在设置。 – OVB 2012-07-31 03:34:48

+5

首先从属性文件读入到prop对象中。覆盖变量,然后将其存储... *注意:它将删除所有注释和空格。恕我直言,手动做什么属性文件是用于。 – 2012-07-31 03:40:22

-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()); 
+0

-1,这与OP的问题有什么关系? – epoch 2012-07-31 06:47:18