[英]How to properly save a properties file with special characters
我有一個像這樣的屬性文件:
[flags]
prop1=value
prop2=value
[patterns]
prop3=#.00
prop4=###,##0.00
[other]
prop5=value
當我處理文件時,不僅轉義了井號(#),而且我的所有屬性都亂了。
我的代碼是這樣的:
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
}
我使用props.store()
因為我不知道的另一種方式來保存后的屬性文件props.setProperty()
被調用。
所有這些功勞歸功於Jon Skeet,他指出Java屬性並不是要以這種方式使用,而我需要的是Windows風格的.ini文件。 由於這個建議,我記得很多年前我使用過ini4j
,這就是我在這種情況下需要使用的。
解決方案非常簡單:
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!
}
當使用ini4j
進行保存時,我的屬性將保留在各節中,並且屬性的順序將保留,並且特殊字符(如#)不會轉義。 解決了所有問題。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.