Java使用ResourceBundle类读取properties文件中文乱码的解决方案

Java使用java.util.ResourceBundle类的方式来读取properties文件时不支持中文,要想支持中文必须将文件设置为ISO-8859-1编码格式,这对于开发工具默认为UTF-8来说很不友好,而且就算用ISO-8859-1编码,当其他人将这个项目导入开发工具时很容易出现这个properties文件中的内容有乱码(前提是该文件中包含中文)。

//传统的解决方式:文件设置为ISO-8859-1编码格式

public static void main(String[] args) {
    ResourceBundle rb = ResourceBundle.getBundle("weixinreply");
    String kefuReply = null;
    try {
        //这样直接读取中文会乱码
        kefuReply = rb.getString("kefureply_festival");
        System.out.println("kefuReply=" + kefuReply);
        //这样读取中文不会乱码
        kefuReply = new String(rb.getString("kefureply_festival").getBytes("ISO-8859-1"),"GBK");/
        System.out.println("kefuReply=" + kefuReply);
    } catch (UnsupportedEncodingException e) {
        e.printStackTrace();
    }
}

//更加人性化的解决方式:文件设置为UTF-8编码格式,并且在spring加载properties文件时指定为UTF-8编码格式,在使用的类中通过spring的 @Value("${key}")注解来获取properties文件中对应的值。
app-env-config.xml文件中定义如下内容

<bean id="propertyConfigurer"
    class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
    <property name="fileEncoding" value="UTF-8"/>
    <property name="locations">
        <list>
            <value>classpath:weixinreply.properties</value>
        </list>
    </property>
</bean>


app-env-config.xml需要在applicationContext.xml文件中引入,这样才能保证 @Value("${key}")注解在Controller层和Service层都能获取到值,否者很容易造成 @Value("${key}")注解在Controller层获取不到值而报错。

参考:

https://blog.csdn.net/zsg88/article/details/74852942

https://blog.csdn.net/J3oker/article/details/53839210

https://blog.csdn.net/Weiral/article/details/52875307

https://blog.csdn.net/qq_21033663/article/details/78067983

https://blog.csdn.net/Brookes/article/details/1508539

https://blog.csdn.net/joecheungdishuiya/article/details/6304993

全文完

:)

版权声明:本文为博主原创文章,未经博主允许不得转载。

原文地址:https://www.cnblogs.com/poterliu/p/10159577.html

联系邮箱:[email protected]

联系微信:poterliu

或者扫二维码

猜你喜欢

转载自www.cnblogs.com/poterliu/p/10159577.html