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()
- Read the properties file into a Properties object.
- Add the new properties.
- 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.
精彩评论