How to use UTF-8 in resource properties with ResourceBundle

后端 未结 16 2227
难免孤独
难免孤独 2020-11-22 03:28

I need to use UTF-8 in my resource properties using Java\'s ResourceBundle. When I enter the text directly into the properties file, it displays as mojibake.

16条回答
  •  无人及你
    2020-11-22 03:43

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

    I was particularly nervous as this could slow down performance of my application... however, after implementing this, it looks like as if my application is faster now.. i think it is because, i am now directly accessing the properties instead of letting JSF parse its way into accessing properties... i specifically pass Boolean argument in this call because i know some of the properties would not be translated and do not need to be in utf8 format...

    Now I have saved my properties file in UTF8 format and it is working fine as each user in my application has a referent locale preference.

提交回复
热议问题