1

I have a .properties file which have number of comments in it, when I try to update the content of the file other than the comments, even though my comments are disappearing, how to retain my comments?

Here is the config.properties file:

#name of user
name=user1
#id of user
id=id1

and the code to update the properties file, I used

public class SetLog {
    public static void setPath()
    {
        File file = new File("./config.properties");
           Properties prop = new Properties();
           FileInputStream objInput = null;
           try {
            objInput = new FileInputStream(file);
            prop.load(objInput);
            objInput.close();

        FileOutputStream out = new FileOutputStream("./config.properties");
//update the content
               prop.setProperty("name", "user2");
              prop.store(out, null);
               out.close();
            } catch (Exception e) {}              
    }

}

After I run the above code, properties file content changed to:

name=user2
id=id1

But I want in this format:

 #name of user
 name=user2
 #id of user
 id=id1

How to retain my comments, please help!

sunpat
  • 389
  • 2
  • 7
  • 28
  • Maybe the XML format? storeToXML and loadFromXML? That would facilitate using Unicode in the form of UTF-8 too. – Joop Eggen May 26 '15 at 11:05

2 Answers2

1

This has been answered in a similar question: Adding comments in a Property File. Basically it boils down to using the Apache Commons extension to read and write Property Files.

Community
  • 1
  • 1
Brett Walker
  • 3,566
  • 1
  • 18
  • 36
0

Try to read the characters in the file and ignore those lines beginning with # .

See this link

Aman Mohammed
  • 2,878
  • 5
  • 25
  • 39
  • I think the OP desires to _maintain_ comments. Which are not kept in Properties and hence disappear on storing a Properties. – Joop Eggen May 26 '15 at 11:14
  • yes, once the comments are read, they can be written back to the file when the file is being updated with new properties. In fact, even better, comments can be updated with newer comment history and\or date time stamp. – Aman Mohammed May 26 '15 at 11:19
  • @E2241, I kind of need the solution of the problem mentioned in the link you provided, but I am not able to understand the code, can't we achieve it in a simple way where we can keep our comments as it is while updating the key values? – sunpat May 26 '15 at 14:02
  • I am afraid there is no other built in class for Properties at least of which I am aware. You will have to read the lines from the file beginning with # and then write them back for the comments. – Aman Mohammed May 27 '15 at 09:56