您的位置:首页 > 编程语言 > Java开发

java.util.ResourceBundle读取properties文件

2017-05-11 16:25 399 查看

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。这一点很給力)
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  国际化 java ResourceBu