繁体   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