开发者

How do I edit a properties file without trashing the rest of it

开发者 https://www.devze.com 2023-04-09 03:59 出处:网络
Example.properties user=somePerson env=linux file=mpg properties.java class propertiestTest.java { Properties props = new Properties();

Example.properties

user=somePerson
env=linux
file=mpg

properties.java class

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

     props.store(new FileOutputStream(propsFile)开发者_JAVA技巧, "");
}

reseult of Example.properties

user=GodIsUser

and all other entries are deleted


You need to populate it from the file first using 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), "");


You should use props.load(inStream) to load the existing props first.
first use Properties.load(), and only after it: modify the properties by using Properties.setProperty()


  1. Read the properties file into a Properties object.
  2. Add the new properties.
  3. Store the newly updated Properties object.

Step 1 above is the key.


You can use 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), "");


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();
        } 

If there is a need close the file , do it as mentioned above.

0

精彩评论

暂无评论...
验证码 换一张
取 消