Java基础之国际化

来源:互联网 发布:安知玉如意txt书本网 编辑:程序博客网 时间:2024/06/01 20:21

国际化资源文件

  • 各语言资源文件命名规范: 自定义名_语言代码_国别代码.properties;
  • 默认资源文件命名规范: 自定义名.properties;

资源文件都必须是ISO-8859-1编码,因此,对于所有非西方语系的处理,都必须先将之转换为Java Unicode Escape格式。转换方法是通过JDK自带的工具native2ascii.

test_zh_CN.properties

aaa=\u597d bbb=\u591a\u8c22

test_en_US.properties

aaa=good bbb=thanks

java.util.ResourceBundle

功能:国家化资源文件的加载;
加载规则:首先根据指定的语言和地区查找对应的资源文件,如果找不到则使用默认的资源文件。例如,当前语言为zh,地区为CN,如果myres_zh_CN.properties、myres.properties两个文件都存在,则优先会使用myres_zh_CN.properties,当myres_zh_CN.properties不存在时候,会使用默认的myres.properties。

代码示例

import java.util.Locale;import java.util.ResourceBundle;/** * 类描述:国际化资源文件工具类 *  * @author ruipeng.lrp * @since 2017/11/23 *  **/public class ResourceBundleUtil {    public static ResourceBundle getResourceBundle(String bundleKey) {        return ResourceBundle.getBundle(bundleKey);    }    public static ResourceBundle getResourceBundle(String bundleKey, Locale locale) {        return ResourceBundle.getBundle(bundleKey, locale);    }    public static String getString(String bundleKey, String key) {        return ResourceBundle.getBundle(bundleKey).getString(key);    }    public static String getString(String bundleKey, Locale locale, String key) {        return ResourceBundle.getBundle(bundleKey, locale).getString(key);    }    public static void main(String[] args) {        System.out.println(ResourceBundle.getBundle("test").getString("aaa"));        System.out.println(ResourceBundle.getBundle("test", new Locale("en", "US")).getString("aaa"));    }}

      这里写图片描述

原创粉丝点击