How to use the ini files correctly while editing and adding in Java, where reading works with ini4j?

1.1k views Asked by At

How to edit exactly without breaking the lines? I have a file test.ini and i just need to add a new record on it and later only modify it. But the following is crashing my existing file.

File: test.ini:

Existing correct version:

myname=C://
field=A=B

After modify it becomes:

myname=C\://
field=A\=B
newfield=blabla\n

Expected output was:

myname=C://
field=A=B
newfield=blabla

Code:

//import java.util.Properties;
try {
  Properties p = new Properties();
  p.load(new FileInputStream("/var/tmp/test.ini"));
  p.setProperty(key,fieldName);        
  p.store(new FileOutputStream("/var/tmp/test.ini"), null);        
  return p.getProperty(fieldName);
} catch(Exception e) {
  return null;
}
2

There are 2 answers

0
Dan Hardiker On BEST ANSWER

Properties files don't follow the same rules as "ini" files, notably they escape different characters - in your case it's escaping colon and equals within data. See http://en.wikipedia.org/wiki/.properties

You could use ini4j to handle the files in the appropriate way, or handle the escaping yourself after saving.

0
Sennri On

you can use ini4j and dont forget to use Config to change writing settings; for instance:

final Ini properties = new Ini();
Config c = new Config();
c.setFileEncoding(UTF_8);
c.setLineSeparator("\n");
c.setEscape(false);// ← here to avoid redundant '\' before ':'
properties.setConfig(c);
properties.load(is);
// do sth
properties.store(Files.newBufferedWriter(propertyPath, UTF_8));