将resourcebundle读为UTF-8.getString()方法似乎将编码更改为ISO-8859

izo*_*can 11 java encoding properties resourcebundle utf-8

我有幸将完整的工作区,项目和文件的编码更改为UTF-8编码.我们有几个Resourcebundles,用于使用unicode编写特殊字符.我们还希望通过切换到UTF-8来摆脱那个unicode的东西,所以我也改变了Resourcebundles(.properties)文件的编码并替换了Unicode字符.

我们也有德国资源捆绑和一些像

Ä,Ö,Ü,ß.ä,ö,ü以及像"或"这样的特殊字符

在浏览器中未正确显示.例:

Resourcebundleentry:

executeShellCommand.label =Shellkommandoausführen

浏览器结果: 在此输入图像描述

使用Java.util.ResourceBundle.getString(String key)方法读取resourcebundle:

    public String getLocalizedString(ResourceBundle bundle, String key) {
    try {
        System.out.println("getLocalizedString, key: " + key + ", resourcebundle: " + bundle.getString(key));
        return bundle.getString(key);
    } catch (MissingResourceException e) {
        return key;
    }
}
Run Code Online (Sandbox Code Playgroud)

如果我检查上面的Sysout的输出我得到以下: getLocalizedString, key: executeShellCommand.label, resourcebundle: Shellkommando ausführen

似乎getString(key)方法在将字符串从字符串读取到标准resourcbundleencoding(ISO-8859)时更改字符的编码.

我试图解决这个问题:

    public String getLocalizedString(ResourceBundle bundle, String key) {
    try {
        System.out.println("getLocalizedString, key: " + key + ", resourcebundle: " + new String (bundle.getString(key).getBytes(), "UTF-8"));
        return new String (bundle.getString(key).getBytes(), "UTF-8");
    } catch (MissingResourceException e) {
        return key;
    } catch (UnsupportedEncodingException e) {
        return key;
    }
}
Run Code Online (Sandbox Code Playgroud)

这有助于恢复最特殊的角色,但仍然有很多没有正确显示的角色:

在此输入图像描述

我还检查了WebApp的内容类型配置以及获取资源包的每个请求都是utf-8.

有没有人知道如何防止getString() - 方法改变编码或有更好的方法来解决这个问题?

lan*_*ava 11

Java ResourceBundles假设ISO-8859.我认为你需要使用Properties而不是ResourceBundle.

InputStream utf8in = getClass().getClassLoader().getResourceAsStream("/path/to/utf8.properties");
Reader reader = new InputStreamReader(utf8in, "UTF-8");
Properties props = new Properties();
props.load(reader);
Run Code Online (Sandbox Code Playgroud)

  • 我看到[PropertyResourceBundle](http://docs.oracle.com/javase/6/docs/api/java/util/PropertyResourceBundle.html)有一个带有`java.io.Reader`的构造函数.我猜你可以利用它. (2认同)
  • 是的,我终于以这种方式解决了它.以下代码解决了这个问题:@Uwe Allner也谢谢你.`java.io.InputStream applStream = getClass().getClassLoader().getResourceAsStream(applPath); Reader applReader = new InputStreamReader(applStream,"UTF-8"); applBundle = new PropertyResourceBundle(applReader); ` (2认同)
  • 通过这种方式,您实际上正在失去捆绑的全部要点。捆绑软件的好处在于,“ language_country”文件中的属性可以覆盖“ country”文件中的属性,而这些属性也可以覆盖基本文件。看看我的其他答案。这是一个适当的技巧,但我认为您会保持捆绑销售行为。另一个选择是将几个PropertyResourceBundle实例链接在一起(一个用于base,base_language和base_language_country)。请参阅ResourceBundle.setParent()。 (2认同)