Java使用java.util.ResourceBundle类的方式来读取properties文件时不支持中文,要想支持中文必须将文件设置为ISO-8859-1编码格式,这对于开发工具默认为UTF-8来说很不友好,而且就算用ISO-8859-1编码,当其他人将这个项目导入开发工具时很容易出现这个properties文件中的内容有乱码(前提是该文件中包含中文)。
//传统的解决方式:文件设置为ISO-8859-1编码格式
1public static void main(String[] args) { 2 ResourceBundle rb = ResourceBundle.getBundle("weixinreply"); 3 String kefuReply = null; 4 try { 5 //这样直接读取中文会乱码 6 kefuReply = rb.getString("kefureply_festival"); 7 System.out.println("kefuReply=" + kefuReply); 8 //这样读取中文不会乱码 9 kefuReply = new String(rb.getString("kefureply_festival").getBytes("ISO-8859-1"),"GBK");/ 10 System.out.println("kefuReply=" + kefuReply); 11 } catch (UnsupportedEncodingException e) { 12 e.printStackTrace(); 13 } 14}
//更加人性化的解决方式:文件设置为UTF-8编码格式,并且在spring加载properties文件时指定为UTF-8编码格式,在使用的类中通过spring的 @Value("${key}")注解来获取properties文件中对应的值。
app-env-config.xml文件中定义如下内容
1<bean id="propertyConfigurer" 2 class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer"> 3 <property name="fileEncoding" value="UTF-8"/> 4 <property name="locations"> 5 <list> 6 <value>classpath:weixinreply.properties</value> 7 </list> 8 </property> 9</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
全文完
:)
原文地址: