我需要使用UTF-8在我的资源属性使用Java的ResourceBundle。当我直接在属性文件中输入文本时,它显示为mojibake。

我的应用程序运行在谷歌应用程序引擎。

谁能给我举个例子?我找不到这份工作。


当前回答

注意:在Java <= 8 Java属性文件应该编码在ISO 8859-1!

ISO 8859-1字符编码。 不能直接输入的字符 用这种编码表示可以 使用Unicode转义符编写;只有 允许输入一个“u”字符 转义序列。

Java文档

如果你真的想这样做:看看: Eclipse中的Java属性UTF-8编码——有一些代码示例


因为Java 9:属性文件是用UTF-8编码的,所以应该没有问题/疑问

在Java SE 9中,属性文件以UTF-8编码方式加载。在以前的版本中,ISO-8859-1编码用于加载属性资源包。

(https://docs.oracle.com/javase/9/intl/internationalization -改进- jdk 9. - htm # jsint guid - 9 - dcdb41c a989 - 4220 - 8140 - dbfb844a0fca)

其他回答

打开设置/首选项对话框(Ctrl + Alt + S),然后单击编辑器和文件编码。

然后,在底部,您将找到属性文件的默认编码。选择您的编码类型。

或者,您可以在资源包中使用unicode符号而不是文本(例如“ів”等于\u0456\u0432)

看这个:http://docs.oracle.com/javase/6/docs/api/java/util/Properties.html#load(java.io.Reader)

属性接受Reader对象作为参数,您可以从InputStream创建该对象。

在创建时,你可以指定Reader的编码:

InputStreamReader isr = new InputStreamReader(stream, "UTF-8");

然后将这个Reader应用到load方法:

prop.load(isr);

顺便说一句:从.properties文件中获取流:

 InputStream stream = this.class.getClassLoader().getResourceAsStream("a.properties");

顺便说一句:从InputStreamReader获取资源包:

ResourceBundle rb = new PropertyResourceBundle(isr);

希望这能帮助到你!

As one suggested, i went through implementation of resource bundle.. but that did not help.. as the bundle was always called under en_US locale... i tried to set my default locale to a different language and still my implementation of resource bundle control was being called with en_US... i tried to put log messages and do a step through debug and see if a different local call was being made after i change locale at run time through xhtml and JSF calls... that did not happend... then i tried to do a system set default to a utf8 for reading files by my server (tomcat server).. but that caused pronlem as all my class libraries were not compiled under utf8 and tomcat started to read then in utf8 format and server was not running properly... then i ended up with implementing a method in my java controller to be called from xhtml files.. in that method i did the following:

        public String message(String key, boolean toUTF8) throws Throwable{
            String result = "";
            try{
                FacesContext context = FacesContext.getCurrentInstance();
                String message = context.getApplication().getResourceBundle(context, "messages").getString(key);

                result = message==null ? "" : toUTF8 ? new String(message.getBytes("iso8859-1"), "utf-8") : message;
            }catch(Throwable t){}
            return result;
        }

我特别紧张,因为这可能会降低我应用程序的性能……然而,在实现这个之后,看起来好像我的应用程序现在更快了。我认为这是因为,我现在直接访问属性,而不是让JSF解析其访问属性的方式…我特别在这个调用中传递布尔参数,因为我知道一些属性不会被翻译,不需要在utf8格式…

现在我已经以UTF8格式保存了我的属性文件,它工作正常,因为我的应用程序中的每个用户都有一个引用的区域设置偏好。

http://sourceforge.net/projects/eclipse-rbe/

如前所述,属性文件应该用ISO 8859-1编码

您可以使用上面的eclipse IDE插件为您进行Unicode转换。

不管怎样,我的问题是文件本身的编码是错误的。使用iconv对我很有效

iconv -f ISO-8859-15 -t UTF-8  messages_nl.properties > messages_nl.properties.new