簡體   English   中英

Java沒有將“ \\ u”寫入屬性文件

[英]Java not writing “\u” to properties file

我有一個屬性文件,該文件將德語字符映射到其十六進制值(00E4)。 我必須使用“ iso-8859-1”對該文件進行編碼,因為這是顯示德語字符的唯一方法。 我想做的是遍歷德語單詞,檢查這些字符是否出現在字符串中的任何位置,以及是否確實用十六進制格式替換了該值。 例如,將德國char替換為

該代碼很好地替換了字符,但是在一個反沖中,我得到了兩個\\\ä 您可以在代碼中看到我正在使用"\\\\u\u0026quot;嘗試打印\\u\u003c/code> ,但這不會發生。 關於我在哪里出問題的任何想法?

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();
}

關鍵是您不是在編寫簡單的文本文件,而是在編寫Java屬性文件。 在屬性文件中,反斜杠字符是轉義字符,因此,如果您的屬性值包含反斜杠,則Java很適合為您轉義-這不是您所需要的。

您可能試圖通過編寫可以作為屬性文件讀回的plian文本文件來規避Java的屬性文件機制,但這將意味着手動執行Properties類自動提供的所有格式設置。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM