Update property using Properties

73 views Asked by At

I want to add new property to an existing file. Whenever, I add the new property, the entire file gets overwritten. Is there a way to update the file and not overwrite property.

FileOutputStream fo = new FileOutputStream(PROPERTIES_FILE);
    Properties pr = new Properties();
    pr.setProperty("Key1", "KeyValue");
    try {
        pr.store(fo, " Comments");

    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

(1) Now if I want to add a new property called Key2 and the set a value KeyValue2. Is it possible ?

(2) Also when I deploy in tomcat, only when I give the absolute path, the file is getting updated. Is there a way to find the file location at runtime. Because when I run test case, the file will be present locally and the path will be different.

(3) Is there a way to leverage classpath in anyway for this.

Thanks in advance!

1

There are 1 answers

0
Jeevan Varughese On BEST ANSWER

**I am writing it down since I did not find clear answer for the problem mentioned **

(1) Now if I want to add a new property called Key2 and the set a value KeyValue2. Is it possible ?

**Yes it is possible. The key to understanding here is that, the properties object will be store on calling 'store' api. Here appending does not happens. The file will be overwritten by the contents of the properties object. THE API DOES NOT SUPPORT APPENDING IT. The solution this problem will be to : 1) Load the properties from the same file 2) Update the new property or existing property 3) then store using the output stream

IN THIS WAY THE CONTENT OF THE FILE WILL NOT BE LOST**

(2) Also when I deploy in tomcat, only when I give the absolute path, the file is getting updated. Is there a way to find the file location at runtime. Because when I run test case, the file will be present locally and the path will be different.

** There are two ways to do it 1) Make sure that the file is present in the classpath. If present in the classpath, we need not give absolute path before the filename

2) Provide another class which set the path. In this way, the path can be set when running the testcases. (TESTNG/JUNIT)**

(3) Is there a way to leverage classpath in anyway for this.

** Already covered above **

Hope this helps