为什么瑞典语中的文字出现在瑞典语中,出现在gibberish中? [复制
-
09-10-2019 - |
题
可能的重复:
如何使用资源键在资源属性中使用UTF-8
我想允许国际化用于我的Java Swing应用程序。我使用捆绑文件将所有标签保留在其中。
作为测试,我试图将瑞典标题设置为 JButton
. 。因此,在我写的捆绑文件中:
nextStepButton=nästa
在我写的Java代码中:
nextStepButton.setText(bundle.getString("nextStepButton"));
但是该按钮的标题字符在运行时出现错误:
我正在使用支持Unicode的tahoma字体。当我通过代码手动设置按钮标题时,它看起来不错:
nextStepButton.setText("nästa");
知道为什么它在捆绑文件中失败了吗?
--------------------------------------------> 编辑:编码标题:
我尝试使用代码来编码来自捆绑文件的文本:
nextStepButton.setText(new String(bundle.getString("nextStepButton").getBytes("UTF-8")));
结果仍然是:
解决方案
按照 Javadoc, ,使用ISO-8859-1读取属性文件。
..输入/输出流在ISO 8859-1字符编码中编码。可以使用Unicode Escapes编写该编码中无法直接表示的字符;在逃生序列中仅允许单个“ U”字符。本机2aScii工具可用于将属性文件转换为其他字符编码。
除了使用本机2aScii工具将UTF-8属性文件转换为ISO-8859-1属性文件外,您还可以使用自定义 ResourceBundle.Control
这样您就可以控制属性文件的加载并在那里使用UTF-8。这是一个开球示例:
public class UTF8Control extends Control {
public ResourceBundle newBundle
(String baseName, Locale locale, String format, ClassLoader loader, boolean reload)
throws IllegalAccessException, InstantiationException, IOException
{
// The below is a copy of the default implementation.
String bundleName = toBundleName(baseName, locale);
String resourceName = toResourceName(bundleName, "properties");
ResourceBundle bundle = null;
InputStream stream = null;
if (reload) {
URL url = loader.getResource(resourceName);
if (url != null) {
URLConnection connection = url.openConnection();
if (connection != null) {
connection.setUseCaches(false);
stream = connection.getInputStream();
}
}
} else {
stream = loader.getResourceAsStream(resourceName);
}
if (stream != null) {
try {
// Only this line is changed to make it to read properties files as UTF-8.
bundle = new PropertyResourceBundle(new InputStreamReader(stream, "UTF-8"));
} finally {
stream.close();
}
}
return bundle;
}
}
使用如下:
ResourceBundle bundle = ResourceBundle.getBundle("com.example.i18n.text", new UTF8Control());
这样,您就无需使用本机2aScii工具来麻烦,最终会得到更好的可维护属性文件。
也可以看看:
其他提示
看一眼 Java国际化常见问题解答. 。如果您将非ASCII字符放在您的 .properties
文件,您必须使用 本机2 工具。那么一切都应该起作用。
问题在于资源捆绑属性文件是在UTF-8中编码的,但是您的应用程序正在使用Latin-1加载它。
如果将“拉丁语小a进行透射率”(拉丁语-1或0000E4中的e4作为unicode codepoint),并将其表示为UTF-8,则获得C3 A4。如果您将这些视为拉丁-1字节,则会获得“带有tilde的拉丁大写字母A”和“正方形”货币标志“字符”字符……这就是字符在按钮的屏幕截图中显示的方式!
(顺便说一句,这是您由于使用错误的字符编码而获得的杂交的新杂志。 Mojibake. 。通过在对话中使用朋友,使您的朋友感到困惑。)