java - How to properly save a properties file with special characters -


i have property file this:

[flags] prop1=value prop2=value [patterns] prop3=#.00 prop4=###,##0.00 [other] prop5=value 

when process file, not pound signs escaped (#), properties out of order.

my code this:

properties props = new properties();  fileinputstream in = null; try {    in = new fileinputstream(prop_file);    reader reader = new inputstreamreader(in, standardcharsets.utf_8);    props.load(reader); } catch (ioexception e) {    // log exception } {    if (in != null)    {       try       {          in.close();       }       catch (ioexception e)       {          // log exception       }    } }  props.setproperty("prop5", "othervalue"); try {    outputstreamwriter w = new outputstreamwriter(new fileoutputstream(ini_file), standardcharsets.utf_8);    props.store(w, null); } catch (ioexception e) {    // log exception } 

i using props.store() because not know of way save properties file after props.setproperty() called.

all credit goes jon skeet pointing out java properties not meant used way, , needed windows-style .ini file. because of suggestion, remember used ini4j many years ago , needed use in case.

the solution quite simple:

try {    wini ini = new wini(new file(prop_file));    ini.put("others", "prop5", value); // "others" section, "prop5" key, , "value" self-explanatory.    ini.store(); // ini file saved } catch (ioexception e) {    // log problem... whatever! } 

when using ini4j save, properties preserved in sections, , order of properties preserved, , special characters (like #) not escaped; addresses of issues.


Comments