javapropertiesdivider

How to change the Properties.store() divider symbol from "=" to ":"?


I recently found out about java.util.Properties, which allows me to write and read from a config without writing my own function for it.

I was excited since it is so easy to use, but later noticed a flaw when I stored the modified config file.

Here is my code, quite simple for now:

FileWriter writer = null;
Properties configFile = new Properties();
configFile.load(ReadFileTest.class.getClassLoader().getResourceAsStream("config.txt"));

String screenwidth = configFile.getProperty("screenwidth");
String screenheight = configFile.getProperty("screenheight");
System.out.println(screenwidth);
System.out.println(screenheight);
configFile.setProperty("screenwidth", "1024");
configFile.setProperty("screenheight", "600");
try {
    writer = new FileWriter("config.txt" );
    configFile.store(writer, null);
} catch (IOException e) {
    e.printStackTrace();
}
writer.flush();
writer.close();

The problem I noticed was that the config file I try to edit is stored like this:

foo: bar
bar: foo
foobar: barfoo

However, the output after properties.store(writer, null) is this:

foo=bar
bar=foo
foobar=barfoo

The config file I edit is not for my program, it is for an other application that needs the config file to be in the format shown above with : as divider or else it will reset the configuration to default.

Does anybody know how to easily change this?

I searched through the first 5 Google pages now but found noone with a similar problem. I also checked the Javadoc and found no function that allows me to change it without writing a class for myself. I would like to use Properties for now since it is there and quite easy to use. I also got the idea of just replacing all = with : after I saved the file but maybe someone got a better suggestion?


Solution

  • Don't use a tool that isn't designed for the task - don't use Properties here. Instead, I'd just write your own - should be easy enough.

    You can still use a Properties instance as your "store", but don't use it for serializing the properties to text. Instead, just use a FileWriter, iterate through the properties, and write the lines yourself - as key + ": " + value.