java.util.ResourceBundle读取properties文件

ResourceBundle类的作用

基本作用就是读取资源中的properties文件

实际应用:国际化

该类能够使你的程序
- be easily localized, or translated, into different languages
- handle multiple locales at once
- be easily modified later to support even more locales

实例

国际化中Properties文件的命名格式为:自定义名字语言国家.properties
比如英语和中文的写法分别是:errormsg_en_US.properties、errormsg_zh_CN.properties
并在两个文件中添加相应的内容

error.register.phoneDoesNotExist=The phone number does not exist
error.register.phoneDoesNotExist=电话号码不存在
Java代码如下:
import java.util.Locale;
import java.util.ResourceBundle;


public class TestResourceBundle {


    public static void main(String[] args) {

        printMessage(Locale.getDefault());//根据当前系统而定,
        printMessage(new Locale("zh", "CN"));
        printMessage(new Locale("en", "US"));

    }

    public static void printMessage(Locale locale) {
        ResourceBundle resourceBundle = ResourceBundle.getBundle("errormsg", locale); 
        System.out.println(resourceBundle.getString("error.register.phoneDoesNotExist")); 
    }

}

控制台输出:
电话号码不存在(我的是中文系统,所以肯定输出了中文)
电话号码不存在
Sorry, the phone number does not exist

典型问题:Save could not be complete, some characters cannot be mapped using ISO-8859-1

普通的Properties的编码格式是ISO-8859-1,所以保存西方语系的字母时不会报错,当你输入中文或日文等文字时就保存不了了。
这里写图片描述

两种解决方法
1. 直接点Save as UTF-8(不推荐)

但是问题来了,当你调用resourceBundle.getString("xxx")打印出来时变成乱码。有个解决方法,利用String类做编码转换

new String(resourceBundle.getString("xxx").getBytes("ISO-8859-1"), "UTF-8"); 

该方法有点笨,非常不方便,只要你用到中文的地方都要用一次New String作转换,对于程序员来说简直就是噩梦,于是聪明的开发者开发出了一种插件。

2. 下载Eclipse插件:propertiesEditor:(推荐)

该插件的作用是把中文自动转换为unicode格式。
把下载到的插件中的plugins和futures分别添加Eclipse的plugins和futures文件夹中,重启Eclipse。你会发现
porperties文件的图标改变了。
这里写图片描述
说明插件安装成功。然后我们就可以Open with PropetiesEditor,愉快编辑和保存, 不会出现Save could not be complete这个问题了。
(PS: 虽然把中文自动转换为unicode格式,但是在编辑时中文还是显示为中文,不会是unicode。这一点很給力)

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值