《疯狂Java讲义》(二十三)---- 国际化与格式化

  • Java国际化思路

  将程序中的标签/提示等信息放在资源文件中,程序需要支持哪个国家/语言环境,就对应提供相应的资源文件。资源文件的内容是key-value对,key是不变的,但value则随不同的国家语言而改变。

  • Java支持的国家和语言

  通过调用Locale类的getAvailableLocales()方法,可以获取Java所支持的国家和语言。  

  Locale[] localeList = Locale.getAvailableLocales()

程序国际化示例:

step1: 创建message.properties文件

  内容为

  hello=你好!

step2: 创建message_en_US.properties文件

  内容为

  hello=Welcome You!

step3: 使用native2ascii工具(在%JAVA_HOME%/bin路径下找到)处理message.properties文件

  因为mesage.properties包含非西欧字符,必须使用native2ascii工具来生成我们需要的资源文件,对于hello=Welcome You!则不需要。

  语法格式:

  native2ascii 资源文件  目的资源文件

  在cmd中输入

  native2ascii message.properties message_zh_CN.properties

  将生成message_zh_CN.properties文件

step4: 在程序中实现国际化

  

import java.util.Locale;
import java.util.ResourceBundle;

public class HelloWorld {

    public static void main(String[] args) {
    //取得系统默认的国家/语言环境 Locale myLocale
= Locale.getDefault();
    //根据指定的国家和语言环境加载资源文件 ResourceBundle bundle
= ResourceBundle.getBundle("message", myLocale); System.out.println(bundle.getString("hello")); } }

打印出“你好!”

 如果在控制面板中讲机器的语言环境设置为美国,然后再次运行,将打印出“Welcome You!”。

Tip:How to set eclipse console locale/language

Go to Window > Preferences > Java > Installed JREs > select preferred JRE > Edit and then add the following to Default VM arguments:

-Duser.language=en -Duser.country=US

  • 使用MessageFormat处理包含占位符的字符串

step1 : 提供myMess_en_US.properties文件,内容如下

msg=Hello,{0}!Today is {1}.

step2 : 提供myMess.properties文件,内容如下

msg=你好,{0}!今天是{1}。

step3:使用native2ascii命令,将处理后的文件保存为myMess_zh_CN.properties.

step4: 运行如下程序

import java.text.MessageFormat;
import java.util.Date;
import java.util.Locale;
import java.util.ResourceBundle;

public class MessageFormatDemo {

    public static void main(String[] args) {
        Locale currentLocale = null;
        if (args.length==2) {
            currentLocale = new Locale(args[0], args[1]);
        } else {
            currentLocale = Locale.getDefault();
        }
        ResourceBundle bundle = ResourceBundle.getBundle("myMess", currentLocale);
        String msg = bundle.getString("msg");
        System.out.println(MessageFormat.format(msg, "ivy", new Date()));

    }

}
  • 使用SimpleDateFormat格式化日期
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

public class RedisThreadSafeDateFormat {
    private ThreadLocal<DateFormat> df = new ThreadLocal<DateFormat>() {

        @Override
        protected DateFormat initialValue() {
            return new SimpleDateFormat("EEE MMM dd HH:mm:ss:SSS yyyy");
        }

    };

    public Date parse(String dateString) throws ParseException {
        return df.get().parse(dateString);
    }
    
    public String format(Date date) throws ParseException {
        return df.get().format(date);
    }    
}