i cannot write property
1 posts in topic
Flat View  Flat View

Posted By:   santosh_sharma
Posted On:   Monday, August 19, 2002 08:35 AM

Properties prop = new Properties();
FileOutputStream output = new FileOutputStream"Profile1.txt");
prop.store(output,"my testproperties");
now the problem is if i do as above..
already existing Profile1.txt get replaced by new ..so
how can i actually make changes in a already existing property file..

Re: i cannot write property

Posted By:   michael_dean  
Posted On:   Monday, August 19, 2002 09:13 AM

You need to load the existing properties file, make changes, then write the new properties file. For example:

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Properties;

public class PropertiesDemo {
public static void main(String[] args) {
try {
Properties prop = new Properties();
FileInputStream input = new FileInputStream("Profile1.txt");
prop.setProperty("companyName", "MyCompany");
FileOutputStream output = new FileOutputStream("Profile1.txt");
prop.store(output, "my testproperties");
} catch (IOException e) {
System.err.println("IOException: " + e);


Note that in so doing, calling the write method will remove comments and blank lines that you have included in your properties file. However, as these are ignored by the load(InputStream) method, it will not affect the functionality of your program.

Also notice that instead of using the put(Object, Object) method inherited from HashTable, I used the setProperty(String, String) method defined in Properties. In spite of the fact that most books and references use put(...), you should always use setProperty(...) as it will enforce the use of Strings for keys and values--since both must be Strings. From the javadoc for the class Properties:

Because Properties inherits from Hashtable, the put and putAll methods can be applied to a Properties object. Their use is strongly discouraged as they allow the caller to insert entries whose keys or values are not Strings. The setProperty method should be used instead. If the store or save method is called on a "compromised" Properties object that contains a non-String key or value, the call will fail.

Finally, one small technical detail is you might be interested in--the first argument passed to put(...) or setProperty(...) is the key and the second argument is the value. Your code shows a variable (which I replaced with a String literal) called key for the value of the property.

About | Sitemap | Contact