Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Appending data to properties file, comments disappear & order of data changed [duplicate]

While appending data to properties file, existing comments disappear & order of data is being changed. Please suggest how to avoid it?

data in properties file(before appending the data) along with comments is as follows:

# Setting the following parameters 
# Set URL to test the scripts against
App.URL = https://www.gmail.com
# Enter username and password values for the above Test URL
App.Username = XXXX
App.Password = XXXX

I am adding more data to above properties file as follows:

 public void WritePropertiesFile(String key, String data) throws Exception
{       
    try 
    {
        loadProperties();  
        configProperty.setProperty(key, data);
        File file = new File("D:\\Helper.properties");
        FileOutputStream fileOut = new FileOutputStream(file);
        configProperty.store(fileOut, null);
        fileOut.close();
    } 
    catch (Exception e) 
    {
        e.printStackTrace();
    }
}

calling the above functiona as:

help.WritePropertiesFile("appwrite1","write1");
help.WritePropertiesFile("appwrite2","write2");
help.WritePropertiesFile("appwrite3","write3");

Data is added successfully, however the previously entered comments are disappeared and order of the data is also changed and the properties file(after appending data) is displayed as follows

#Tue Jul 02 11:04:29 IST 2013
App.Password=XXXX
App.URL=https\://www.gmail.com
appwrite3=write3
appwrite2=write2
appwrite1=write1
App.Username=XXXX

I want the data to append at the last ,doesn't want to change the order and doesn't want to remove the previously entered comments. Please let me know if it is possible to implement my requirement?

like image 842
Vikas Avatar asked Jul 02 '13 05:07

Vikas


2 Answers

I recently came to same issue and found the following answer here on StackOverflow: https://stackoverflow.com/a/565996/1990089. It recommends using of Apache Commons Configuration API to deal with properties files, which allows to preserve comments and whitespace. Didn't try this yet myself however.

like image 122
Sergey Makarov Avatar answered Nov 15 '22 00:11

Sergey Makarov


It is not straight forward to preserve the comments of properties file. There are no methods on java.util.Properties to handle comments. Comments are simply ignored when reading the file. As only the key value pairs are loaded when we do properties.load and hence when you save it back the comments are lost. Check the link below, there is one solution to achieve what you need but not the elegant way:

http://www.dreamincode.net/forums/topic/53734-java-code-to-modify-properties-file-and-preserve-comments/

like image 37
Juned Ahsan Avatar answered Nov 15 '22 00:11

Juned Ahsan