大家好,又见面了,我是你们的朋友全栈君。
一、ResourceBundle 简介:
资源束(ResourceBundle)是一个本地化对象。它封装了适用于本地环境的资源; 这个类主要用来解决国际化和本地化问题。国际化和本地化可不是两个概念,两者都是一起出现的。可以说,国际化的目的就是为了实现本地化。
比如对于“取消”,中文中我们使用“取消”来表示,而英文中我们使用“cancel”。若我们的程序是面向国际的(这也是软件发展的一个趋势),那么使用的人群必然是多语言环境的,实现国际化就非常有必要。而ResourceBundle可以帮助我们轻松完成这个任务:当程序需要一个特定于语言环境的资源时(如 String),程序可以从适合当前用户语言环境的资源包(大多数情况下也就是.properties文件)中加载它。这样可以编写很大程度上独立于用户语言环境的程序代码,它将资源包中大部分(即便不是全部)特定于语言环境的信息隔离开来。
这使编写的程序可以:
- 轻松地本地化或翻译成不同的语言
- 一次处理多个语言环境
- 以后可以轻松进行修改,以便支持更多的语言环境
说的简单点,这个类的作用就是读取资源属性文件(properties),然后根据.properties文件的名称信息(本地化信息),匹配当前系统的国别语言信息(也可以程序指定),然后获取相应的properties文件的内容。使用这个类,properties需要遵循一定的命名规范,一般的命名规范是: 自定义名_语言代码_国别代码.properties(LocalStrings_zh_CN.properties),如果是默认的,直接写为:自定义名.properties(LocalStrings.properties)
当在中文操作系统下,如果LocalStrings_zh_CN.properties、LocalStrings.properties两个文件都存在,则优先会使用LocalStrings_zh_CN.properties,当LocalStrings_zh_CN.properties不存在时候,会使用默认的myres.properties。在没有提供语言和地区的资源文件时使用的是系统默认的资源文件。
资源文件都必须是ISO-8859-1编码,因此,对于所有非西方语系的处理,都必须先将之转换为Java Unicode Escape格式。转换方法是通过JDK自带的工具native2ascii; 所以在中文资源文件中最好把中文转换为unicode, 否则可能会因为编译软件编码格式不一致而出现乱码问题
例如:
userConfig.start=\u7528\u6237\u914d\u7f6e\uff1a\u5904\u7406\u5f00\u59cb
二、ResourceBundle的使用
PropertyResourceBundle将本地化的文本存储于Java property文件中。
从ResourceBundle中获取值
- 获取ResourceBundle实例后可以通过下面的方法获得本地化值。
- getObject(String key);
- getString(String key);
- getStringArray(String key);
- 还可以通过keySet()方法获取所有的key。Set keys = bundle.keySet();
- 其它ResourceBundle 方法可以通过查看文档获得。
使用示例:
(1) 新建4个属性文件
my_en_US.properties:cancelKey=cancel
my_zh_CN.properties:cancelKey=\u53D6\u6D88(取消)
my_zh.properties:cancelKey=\u53D6\u6D88zh(取消zh)
my.properties:cancelKey=\u53D6\u6D88default(取消default)
(2) 获取bundle
ResourceBundle bundle = ResourceBundle.getBundle("res", new Locale("zh", "CN"));
注意: 其中new Locale(“zh”, “CN”)提供本地化信息,上面这行代码,程序会首先在classpath下寻找my_zh_CN.properties文件,若my_zh_CN.properties文件不存在,则取找my_zh.properties,如还是不存在,继续寻找my.properties,若都找不到就抛出异常。
(3) Test示例
import javax.annotation.Resource;
import java.util.Locale;
import java.util.ResourceBundle;
/**
* @author OovEver
* 2018/1/14 22:12
*/
public class Main {
public static void main(String args[]) {
ResourceBundle bundle = ResourceBundle.getBundle("my", new Locale("zh", "CN"));
String cancel = bundle.getString("cancelKey");
System.out.println(cancel);
bundle = ResourceBundle.getBundle("my", Locale.US);
cancel = bundle.getString("cancelKey");
System.out.println(cancel);
bundle = ResourceBundle.getBundle("my", Locale.getDefault());
cancel = bundle.getString("cancelKey");
System.out.println(cancel);
bundle = ResourceBundle.getBundle("my", Locale.GERMAN);
cancel = bundle.getString("cancelKey");
System.out.println(cancel);
bundle = ResourceBundle.getBundle("my");
for (String key : bundle.keySet()) {
System.out.println(bundle.getString(key));
}
}
}
(4) 输出结果
取消
cancel
取消
取消
取消
(5) 分析
前面三个分别按照zh_CN,US,默认的结果输出,第四个由于我们未定义GERMAN属性文件,这时ResourceBundle为我们提供了一个fallback(也就是一个备用方案),这个备用方案就是根据当前系统的语言环境来得到的本地化信息。所以若是找不到GERMAN的,之后就会去找CHINA了,所以找到了res_zh_CH.properties这个资源包。最后一个是若有多个属性文件,可以按照Map的形式遍历,获得属性文件内的各个值。
三、Tomcat中的ResourceBundle使用
Tomcat 的国际化管理是根据java文件包分类的; (比如操作系统为中文,那么通ResourceBundle.getBundle(org.apache.XXXX)所得到的本地资源束所指向的文件既是org.apaceh包下的XXXX_CN.properties)
Tomcat 维护了一个StringManager的集合。Tomcat将国际化资源信息存储在相应的包中。
(1) StringManager类中维护了一个StringManager集合
private static Hashtable managers = new Hashtable();
(2) StringManager类实现了对ResourceBundle资源束的管理,是ResourceBundle的封装
private final ResourceBundle bundle;
(3) 构造方法中实现了通过包名来取得本地环境指定包下的bundle
private StringManager(String packageName, Locale locale) {
String bundleName = packageName + “.LocalStrings”;
ResourceBundle bnd = null;
try {
if (locale.getLanguage().equals(Locale.ENGLISH.getLanguage())) {
locale = Locale.ROOT;
}
bnd = ResourceBundle.getBundle(bundleName, locale);
} catch (MissingResourceException ex) {
. . .
}
bundle = bnd;
if (bundle != null) {
Locale bundleLocale = bundle.getLocale();
if (bundleLocale.equals(Locale.ROOT)) {
this.locale = Locale.ENGLISH;
} else {
this.locale = bundleLocale;
}
} else {
this.locale = null;
}
}
(4) 最后通过bundle.getString(key);方法,即可得到本地资源信息
public String getString(final String key, final Object… args) {
String value = getString(key);
if (value == null) {
value = key;
}MessageFormat mf = new MessageFormat(value);
mf.setLocale(locale);
return mf.format(args, new StringBuffer(), null).toString();
}
StringManager类:
package org.apache.tomcat.util.res;
import java.text.MessageFormat;
import java.util.Enumeration;
import java.util.Hashtable;
import java.util.LinkedHashMap;
import java.util.Locale;
import java.util.Map;
import java.util.MissingResourceException;
import java.util.ResourceBundle;
public class StringManager {
private static int LOCALE_CACHE_SIZE = 10;
//此StringManager的ResourceBundle
private final ResourceBundle bundle;
private final Locale locale;
/**
* Creates a new StringManager for a given package. This is a
* private method and all access to it is arbitrated by the
* static getManager method call so that only one StringManager
* per package will be created.
*
* @param packageName Name of package to create StringManager for.
*/
private StringManager(String packageName, Locale locale) {
String bundleName = packageName + ".LocalStrings";
ResourceBundle bnd = null;
try {
// The ROOT Locale uses English. If English is requested, force the
// use of the ROOT Locale else incorrect results may be obtained if
// the system default locale is not English and translations are
// available for the system default locale.
if (locale.getLanguage().equals(Locale.ENGLISH.getLanguage())) {
locale = Locale.ROOT;
}
bnd = ResourceBundle.getBundle(bundleName, locale);
} catch (MissingResourceException ex) {
// Try from the current loader (that's the case for trusted apps)
// Should only be required if using a TC5 style classloader structure
// where common != shared != server
ClassLoader cl = Thread.currentThread().getContextClassLoader();
if (cl != null) {
try {
bnd = ResourceBundle.getBundle(bundleName, locale, cl);
} catch (MissingResourceException ex2) {
// Ignore
}
}
}
bundle = bnd;
// Get the actual locale, which may be different from the requested one
if (bundle != null) {
Locale bundleLocale = bundle.getLocale();
if (bundleLocale.equals(Locale.ROOT)) {
this.locale = Locale.ENGLISH;
} else {
this.locale = bundleLocale;
}
} else {
this.locale = null;
}
}
/**
* Get a string from the underlying resource bundle or return null if the
* String is not found.
*
* @param key to desired resource String
*
* @return resource String matching <i>key</i> from underlying bundle or
* null if not found.
*
* @throws IllegalArgumentException if <i>key</i> is null
*/
public String getString(String key) {
if (key == null){
String msg = "key may not have a null value";
throw new IllegalArgumentException(msg);
}
String str = null;
try {
// Avoid NPE if bundle is null and treat it like an MRE
if (bundle != null) {
str = bundle.getString(key);
}
} catch (MissingResourceException mre) {
//bad: shouldn't mask an exception the following way:
// str = "[cannot find message associated with key '" + key +
// "' due to " + mre + "]";
// because it hides the fact that the String was missing
// from the calling code.
//good: could just throw the exception (or wrap it in another)
// but that would probably cause much havoc on existing
// code.
//better: consistent with container pattern to
// simply return null. Calling code can then do
// a null check.
str = null;
}
return str;
}
/**
* Get a string from the underlying resource bundle and format
* it with the given set of arguments.
*
* @param key The key for the required message
* @param args The values to insert into the message
*
* @return The request string formatted with the provided arguments or the
* key if the key was not found.
*/
public String getString(final String key, final Object... args) {
String value = getString(key);
if (value == null) {
value = key;
}
MessageFormat mf = new MessageFormat(value);
mf.setLocale(locale);
return mf.format(args, new StringBuffer(), null).toString();
}
/**
* Identify the Locale this StringManager is associated with.
*
* @return The Locale associated with the StringManager
*/
public Locale getLocale() {
return locale;
}
// --------------------------------------------------------------
// STATIC SUPPORT METHODS
// --------------------------------------------------------------
private static final Map<String, Map<Locale,StringManager>> managers =
new Hashtable<>();
/**
* Get the StringManager for a given class. The StringManager will be
* returned for the package in which the class is located. If a manager for
* that package already exists, it will be reused, else a new
* StringManager will be created and returned.
*
* @param clazz The class for which to retrieve the StringManager
*
* @return The instance associated with the package of the provide class
*/
public static final StringManager getManager(Class<?> clazz) {
return getManager(clazz.getPackage().getName());
}
/**
* Get the StringManager for a particular package. If a manager for
* a package already exists, it will be reused, else a new
* StringManager will be created and returned.
*
* @param packageName The package name
*
* @return The instance associated with the given package and the default
* Locale
*/
public static final StringManager getManager(String packageName) {
return getManager(packageName, Locale.getDefault());
}
/**
* Get the StringManager for a particular package and Locale. If a manager
* for a package/Locale combination already exists, it will be reused, else
* a new StringManager will be created and returned.
*
* @param packageName The package name
* @param locale The Locale
*
* @return The instance associated with the given package and Locale
*/
public static final synchronized StringManager getManager(
String packageName, Locale locale) {
Map<Locale,StringManager> map = managers.get(packageName);
if (map == null) {
/*
* Don't want the HashMap to be expanded beyond LOCALE_CACHE_SIZE.
* Expansion occurs when size() exceeds capacity. Therefore keep
* size at or below capacity.
* removeEldestEntry() executes after insertion therefore the test
* for removal needs to use one less than the maximum desired size
*
*/
map = new LinkedHashMap<Locale,StringManager>(LOCALE_CACHE_SIZE, 1, true) {
private static final long serialVersionUID = 1L;
@Override
protected boolean removeEldestEntry(
Map.Entry<Locale,StringManager> eldest) {
if (size() > (LOCALE_CACHE_SIZE - 1)) {
return true;
}
return false;
}
};
managers.put(packageName, map);
}
StringManager mgr = map.get(locale);
if (mgr == null) {
mgr = new StringManager(packageName, locale);
map.put(locale, mgr);
}
return mgr;
}
/**
* Retrieve the StringManager for a list of Locales. The first StringManager
* found will be returned.
*
* @param packageName The package for which the StringManager was
* requested
* @param requestedLocales The list of Locales
*
* @return the found StringManager or the default StringManager
*/
public static StringManager getManager(String packageName,
Enumeration<Locale> requestedLocales) {
while (requestedLocales.hasMoreElements()) {
Locale locale = requestedLocales.nextElement();
StringManager result = getManager(packageName, locale);
if (result.getLocale().equals(locale)) {
return result;
}
}
// Return the default
return getManager(packageName);
}
}
发布者:全栈程序员-用户IM,转载请注明出处:https://javaforall.cn/158190.html原文链接:https://javaforall.cn
【正版授权,激活自己账号】: Jetbrains全家桶Ide使用,1年售后保障,每天仅需1毛
【官方授权 正版激活】: 官方授权 正版激活 支持Jetbrains家族下所有IDE 使用个人JB账号...