简体   繁体   中英

How to properly save a properties file with special characters

I have a property file like this:

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

When I process the file, not only the pound signs are escaped (#), but all my properties are out of order.

my code is something like 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
}
finally
{
   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 am using props.store() because I do not know of another way to save the properties file after props.setProperty() is called.

All the credit goes to Jon Skeet for pointing out that Java Properties are not meant to be used this way, and that what I needed was a Windows-style .ini file. Because of this suggestion, I remember I used ini4j many years ago and that is what I needed to use in this case.

The solution is quite simple:

try
{
   Wini ini = new Wini(new File(PROP_FILE));
   ini.put("others", "prop5", value); // "others" is the section, "prop5" the key, and "value" is self-explanatory.
   ini.store(); // INI file is saved
}
catch (IOException e)
{
   // log problem... do whatever!
}

When using ini4j to save, my properties are preserved in sections, and the order of properties is preserved, and special characters (like #) are not escaped; which addresses ALL of the issues.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM