2017-07-14 89 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'),幷包含保存時轉義的一個反斜槓。 –