zuiliushang / Java-Web-

The note of Java Web
8 stars 1 forks source link

JAVA开发-国际化 #27

Open zuiliushang opened 8 years ago

zuiliushang commented 8 years ago

固定文本元素的国际化

属性文件是不能保存中文的

username=username
password=password
submit=submit

        resource_en.properties文件
username=\u7528\u6237\u540d
password=\u5bc6\u7801
submit=\u63d0\u4ea4

        resource_zh.properties文件

编程实现固定文本的国际化

Locale currentLocale = Locale.getDefault();
ResourceBundle myResources = ResourceBundle.getBundle(basename,currentLocale);
    - basename为资源包基名(且必须为完整路径)。
    - 如果与该locale对象匹配的资源包子类找不到。一般情况下,<b>则选用默认资源文件予以显示</b>。
public static void main(String[] args) {
        // TODO Auto-generated method stub
        ResourceBundle bundle = 
ResourceBundle.getBundle("com.zuiliushang.resouce.myproperties",Locale.US);

        String username = bundle.getString("username");
        String password = bundle.getString("password");
        System.out.println(username);
        System.out.println(password);
    }
zuiliushang commented 8 years ago

动态数据的国际化

DateFormat 类(国际化日期)

例如:

    public static void main(String[] args){

        Date date = new Date(); //当前这一刻时间(日期,时间)
        DateFormat dateFormat = DateFormat.getDateInstance(DateFormat.FULL,Locale.CHINA);
        String result = dateFormat.format(date);
        System.out.println(result);

        dateFormat = DateFormat.getTimeInstance(dateFormat.FULL, Locale.CHINA);
        result = dateFormat.format(date);
        System.out.println(result);

        dateFormat = DateFormat.getDateTimeInstance(dateFormat.FULL, 
dateFormat.SHORT,Locale.CHINA);
        result = dateFormat.format(date);
        System.out.println(result);
    }

NumberFormat 类(国际化数字)

方法:

public static void main(String[] args) throws Exception{

        int price = 50;
        NumberFormat nFormat = NumberFormat.getCurrencyInstance(Locale.CHINA);
        String a = nFormat.format(price);
        System.out.println(a);
    }
zuiliushang commented 8 years ago

MessageFormat (动态文本)

如果一个字符串中包含了多个与国际化相关的数据,可以使用 MessageFormat 类对这些数据进行批量处理。

例如:

MessageFormat 类如何进行批量处理呢?

例子:

模式字符串:

MessageFormat 类

    public static void main(String[] args) throws Exception{

        String pattern = "on {0}, a hurricance destroyed {1} houses and caused {2} of damage";
        MessageFormat messageFormat = new MessageFormat(pattern,Locale.CHINA);

        Object[] arr = {new Date(),99,1000000};
        String result = messageFormat.format(arr);
        System.out.println(result);

    }

占位符有三种书写方式:

例子:

    public static void main(String[] args) throws Exception{

        String pattern = "At {0,time,short} on {0,date}, a hurricance destroyed {1} houses and 
caused {2,number,currency} of damage";
        MessageFormat messageFormat = new MessageFormat(pattern,Locale.CHINA);
        Object[] arr = {new java.util.Date(),99,10000000};
        String result = messageFormat.format(arr);
        System.out.println(result);
    }