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

我有幸将完整的工作区,项目和文件的编码更改为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; } } 

如果我检查上面的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; } } 

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

在此处输入图像描述

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

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

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

怎么这是一个黑客!

 public class HackClassLoader extends ClassLoader { public HackClassLoader(ClassLoader parent) { super(parent); } @Override public InputStream getResourceAsStream(String name) { InputStream utf8in = getParent().getResourceAsStream(name); if (utf8in != null) { try { byte[] utf8Bytes = new byte[utf8in.available()]; utf8in.read(utf8Bytes, 0, utf8Bytes.length); byte[] iso8859Bytes = new String(utf8Bytes, "UTF-8").getBytes("ISO-8859-1"); return new ByteArrayInputStream(iso8859Bytes); } catch (IOException ex) { throw new RuntimeException("Could not load " + name, e); } finally { utf8in.close(); } } return null; } } ClassLoader hackLoader = new HackClassLoader(getClass().getClassLoader()); ResourceBundle bundle = ResourceBundle.getBundle("foo", Locale.UK, hackLoader);