国际化程序实现

2020-12-23  本文已影响0人  曾梦想仗剑天涯

国际化程序实现原理

此图来源于李兴华老师

Locale类

//实例化Locale类对象
import java.util.Locale;
public class LocaleApi {
    public static void main(String[] args) {
        Locale loc = new Locale("zh", "CN");
        System.out.println(loc);
    }
}
Locale loc = Locale.getDefault();
Locale loc = Locale.CHINA;

ResourceBundle读取资源文件

//使用ResourceBundle类读取内容
import java.util.ResourceBundle;
public class ResourceBundleApi {
    public static void main(String[] args) {
        ResourceBundle resource = ResourceBundle.getBundle("com.company.Message");
        String val = resource.getString("info");
        System.out.println(val);
    }
}

国际化程序实现

import java.util.ResourceBundle;
public class ResourceBundleApi {
    public static void main(String[] args) {
        ResourceBundle resource = ResourceBundle.getBundle("com.company.Message");
        String val = resource.getString("msg");
        System.out.println(val);
    }
}
import java.util.Locale;
import java.util.ResourceBundle;
public class ResourceBundleApi {
    public static void main(String[] args) {
        Locale loc = new Locale("en", "US");
        ResourceBundle resource = ResourceBundle.getBundle("com.company.Message", loc);
        String val = resource.getString("msg");
        System.out.println(val);
    }
}

消息格式化

import java.text.MessageFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.ResourceBundle;
public class ResourceBundleApi {
    public static void main(String[] args) {
        ResourceBundle resource = ResourceBundle.getBundle("com.company.Message");
        String val = resource.getString("msg");
        //msg=Hello {0} date {1}
        System.out.println(MessageFormat.format(val, "小明", new SimpleDateFormat("yyyy-MM-dd").format(new Date())));
    }
}
上一篇下一篇

猜你喜欢

热点阅读