Bra*_*rad 7 java swing resourcebundle internationalization mojibake
我想允许国际化到我的Java Swing应用程序.我使用捆绑文件来保留其中的所有标签.
作为测试,我试图将瑞典标题设置为a JButton.所以在我写的包文件中:
nextStepButton=nästa
Run Code Online (Sandbox Code Playgroud)
在我写的Java代码中:
nextStepButton.setText(bundle.getString("nextStepButton"));
Run Code Online (Sandbox Code Playgroud)
但是按钮的标题字符在运行时出现错误:

我正在使用支持Unicode的Tahoma字体.当我通过代码手动设置按钮标题时,它看起来很好:
nextStepButton.setText("nästa");
Run Code Online (Sandbox Code Playgroud)
知道为什么它在捆绑文件中失败了吗?
--------------------------------------------> 编辑:编码标题:
我尝试使用代码编码来自bundle文件的文本:
nextStepButton.setText(new String(bundle.getString("nextStepButton").getBytes("UTF-8")));
Run Code Online (Sandbox Code Playgroud)
结果仍然是:

根据javadoc,使用ISO-8859-1读取属性文件.
..输入/输出流以ISO 8859-1字符编码进行编码.无法在此编码中直接表示的字符可以使用Unicode转义编写; 在转义序列中只允许一个'u'字符.native2ascii工具可用于将属性文件转换为其他字符编码或从其他字符编码转换.
除了使用native2ascii工具将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;
}
}
Run Code Online (Sandbox Code Playgroud)
使用方法如下:
ResourceBundle bundle = ResourceBundle.getBundle("com.example.i18n.text", new UTF8Control());
Run Code Online (Sandbox Code Playgroud)
这样您就不需要使用native2ascii工具,并且最终得到了更好的可维护属性文件.
| 归档时间: |
|
| 查看次数: |
3710 次 |
| 最近记录: |