2017-04-05 77 views
0

我有一个属性文件这样的文件:如何妥善保存性能有特殊字符

[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()被调用后属性文件。

+1

这听起来像你试图使用不正确的属性文件。他们不是*要求下令,是的,当他们需要的时候,事情就会逃脱。这听起来像你真的想要像Windows的“ini”文件... –

+0

@JonSkeet,谢谢!就是这样。多年前,我用ini4j来做到这一点。我会仔细看看的。再次,谢谢! – hfontanez

回答

0

全部归功于乔恩斯基特用于指出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拯救,我的属性被保存在部分和属性的顺序被保存,和特殊字符(如#)都没有逃脱;它解决了所有的问题。