如何编辑属性文件而不会破坏其余文件

时间:2011-09-29 17:43:21

标签: java

Example.properties

user=somePerson
env=linux
file=mpg

properties.java类

propertiestTest.java
   {
     Properties props = new Properties();
     props.setProperty("user", "GodIsUser");
     final File propsFile = new File(someDir/Example.properties");

     props.store(new FileOutputStream(propsFile), "");
}

示例属性的结果

user=GodIsUser

并删除所有其他条目

5 个答案:

答案 0 :(得分:7)

您需要先使用props.load

从文件中填充它
final File propsFile = new File("someDir/Example.properties");
Properties props = new Properties();
props.load(new FileInputStream(propsFile));
// make changes
props.save(new FileOutputStream(propsFile), "");

答案 1 :(得分:2)

您应首先使用props.load(inStream)加载现有道具。
首先使用Properties.load(),然后才使用Properties.setProperty()

答案 2 :(得分:1)

  1. 将属性文件读入Properties对象。
  2. 添加新属性。
  3. 存储新更新的“属性”对象。
  4. 上面的第1步是关键。

答案 3 :(得分:1)

您可以使用put

//Load the props
final File propsFile = new File(someDir/Example.properties");

Properties props = load(new FileOutputStream(propsFile));
props.put("user", "GodIsUser");

props.store(new FileOutputStream(propsFile), "");

答案 4 :(得分:0)

try {
        FileInputStream fileName=new FileInputStream(fname);
        Properties props = new Properties();
        props.load(fileName);
        props.setProperty(Id, value);
        fileName.close();
        FileOutputStream outFileName=new FileOutputStream(fname);
        props.store(outFileName, "");
        outFileName.close();
        } catch (IOException io) {

            io.printStackTrace();
        } 

如果需要关闭文件,请按照上述说明进行操作。