2017-07-14 26 views
0

我有一个属性文件,将德文字符映射到它们的十六进制值(00E4)。我必须用“iso-8859-1”编码这个文件,因为这是获得德文字符显示的唯一方法。我想要做的是通过德语单词并检查这些字符是否出现在字符串中的任何位置,以及它们是否用十六进制格式替换该值。例如用\u00E4替换德国字符。Java不写属性文件“ u”

该代码替换字符很好,但在一个反弹,我得到两个像这样\\u00E4。您可以在代码中看到我使用"\\u"来尝试和打印\u,但这不会发生。我要去哪里的任何想法都是错误的?

private void createPropertiesMaps(String result) throws FileNotFoundException, IOException 
{ 
    Properties importProps = new Properties(); 
    Properties encodeProps = new Properties(); 

    // This props file contains a map of german strings 
    importProps.load(new InputStreamReader(new FileInputStream(new File(result)), "iso-8859-1")); 
    // This props file contains the german character mappings. 
    encodeProps.load(new InputStreamReader(
      new FileInputStream(new File("encoding.properties")), 
      "iso-8859-1")); 

    // Loop through the german characters 
    encodeProps.forEach((k, v) -> 
    { 
     importProps.forEach((key, val) -> 
     { 
      String str = (String) val; 

      // Find the index of the character if it exists. 
      int index = str.indexOf((String) k); 

      if (index != -1) 
      { 

       // create new string, replacing the german character 
       String newStr = str.substring(0, index) + "\\u" + v + str.substring(index + 1); 

       // set the new property value 
       importProps.setProperty((String) key, newStr); 

       if (hasUpdated == false) 
       { 
        hasUpdated = true; 
       } 
      } 

     }); 

    }); 

    if (hasUpdated == true) 
    { 
     // Write new file 
     writeNewPropertiesFile(importProps); 
    } 

} 

private void writeNewPropertiesFile(Properties importProps) throws IOException 
{ 
    File file = new File("import_test.properties"); 

    OutputStreamWriter writer = new OutputStreamWriter(new FileOutputStream(file), "UTF-8"); 

    importProps.store(writer, "Unicode Translations"); 

    writer.close(); 
} 
+0

“我收到了两个像这样的”4“。这是一个错字吗?有一个。 – Michael

+0

感谢您指出这一点,似乎你必须逃避这里的反斜杠。但是,这是错误的,这意味着另一个反斜杠。 –

回答

2

问题是,你不是在编写一个简单的文本文件,而是一个java属性文件。在一个属性文件中,反斜杠字符是一个转义字符,所以如果你的属性值包含一个反斜线,Java是如此友好以至于为了逃避它 - 这不是你想要的。

您可能会尝试通过编写一个plian文本文件来绕过Java的属性文件机制,该文本文件可以作为一个proerties文件读回,但这意味着要完成由Properties自动提供的所有格式 - 类手动。

+0

我的房产地图看起来像u = 00E4。所以我没有反应,因为我只在创建新字符串时加入了这个。我推断它会忽略这样的事实,即有两个反斜杠并只打印一个。我想我会在一段时间尝试你的方法,因为这听起来像是一个很好的选择。不要花太长的时间去实施。 –

+0

但新字符串也是一个属性值(转到'importProps'),并包含保存时转义的一个反斜杠。 –