Java学习路线-21:国际化Locale、ResourceBundle、MessageFormat
发布日期:2021-07-01 06:08:09 浏览次数:2 分类:技术文章

本文共 2806 字,大约阅读时间需要 9 分钟。

第11 章 : 国际化程序实现

42 国际化程序实现原理

统一程序代码,根据不同国家实现不同语言描述

需要解决问题:
1、定义保存文字信息
2、根据不同区域语言编码读取文件信息

43 Locale类

Locale类:专门描述区域和语言编码的类

构造方法

public Locale(String language)public Locale(String language, String country)

国家语言代码

中文:zh_CN
美国:en_US

使用示例

import java.util.Locale;class Demo {
public static void main(String[] args){
Locale loc = new Locale("zh", "CN"); System.out.println(loc); // zh_CN }}

读取本地默认环境

Locale loc = Locale.getDefault();System.out.println(loc);// zh_CN

使用常量

Locale loc = Locale.CHINA;System.out.println(loc);// zh_CN

44 ResourceBundle读取资源文件

public static final ResourceBundle getBundle(String baseName)// baseName 没有后缀的文件名

资源文件 message.properties

info="这是消息"

读取实例

import java.io.UnsupportedEncodingException;import java.util.ResourceBundle;class Demo {
public static void main(String[] args) throws UnsupportedEncodingException {
ResourceBundle bundle = ResourceBundle.getBundle("message"); // 解决中文乱码问题 String message = new String(bundle.getString("info").getBytes("ISO-8859-1"), "utf-8"); System.out.println(message); // "这是消息" }}

45 实现国际化程序开发

CLASSPATH 下建立文件

cat Message.propertiesinfo=默认资源 cat Message_zh_CN.propertiesinfo=中文资源 cat Message_en_US.propertiesinfo=英文资源

执行程序会读取中文资源

import java.io.UnsupportedEncodingException;import java.util.ResourceBundle;class Demo {
public static void main(String[] args) throws UnsupportedEncodingException {
ResourceBundle bundle = ResourceBundle.getBundle("message"); // 解决中文乱码问题 String message = new String(bundle.getString("info").getBytes("ISO-8859-1"), "utf-8"); System.out.println(message); // 中文资源 }}

getBundle方法默认加载Locale.getDefault()

public static final ResourceBundle getBundle(String baseName)    {
return getBundleImpl(baseName, Locale.getDefault(), getLoader(Reflection.getCallerClass()), getDefaultControl(baseName)); }

使用重载函数,读取英文资源

Locale locale = Locale.US;ResourceBundle bundle = ResourceBundle.getBundle("message", locale);// 解决中文乱码问题String message = new String(bundle.getString("info").getBytes("ISO-8859-1"), "utf-8");System.out.println(message);// 英文资源

如果没有对应区域编码的资源文件,读取默认资源

读取流程:

指定区域的资源文件 > 默认的本地资源文件 > 公共的资源文件

46 格式化文本显示

格式化方法

public class MessageFormat extends Format {
public static String format(String pattern, Object ... arguments)}

代码示例

import java.text.MessageFormat;import java.text.SimpleDateFormat;import java.util.Date;class Demo {
public static void main(String[] args) {
// 占位符{} String message = "hello {0} date: {1}"; System.out.println(MessageFormat.format(message, "admin", new SimpleDateFormat("yyyy-MM-dd").format(new Date()))); // hello admin date: 2019-11-18 }}

转载地址:https://pengshiyu.blog.csdn.net/article/details/103134301 如侵犯您的版权,请留言回复原文章的地址,我们会给您删除此文章,给您带来不便请您谅解!

上一篇:拼音分词扩展elasticsearch-analysis-pinyin安装
下一篇:Java学习路线-20:正则表达式

发表评论

最新留言

能坚持,总会有不一样的收获!
[***.219.124.196]2024年04月23日 17时42分04秒