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

StackOverflow https://stackoverflow.com/questions/8780722

  •  15-04-2021
  •  | 
  •  

Domanda

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;
}
È stato utile?

Soluzione

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.

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top