Java国际化,使用ResourceBundle的方式读取配置文件

本文介绍了Java中实现国际化的方法,重点讲解了如何利用ResourceBundle读取配置文件,例如messages.properties。通过调整Locale,可以适应不同的语言环境。示例展示了在Tomcat源码中类似的应用。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

如Struts,spring等框架以及Tomcat容器,都是通过ResourceBundle的方式从资源文件(如messages.properties)中自动读取并进行资源绑定的。java.util.ResourceBundle类非常地灵活,可以通过设置的Locale(语言环境)来选择读取的文件,进行国际化。

最近在看Tomcat的源码,看到了Tomcat国际化的实现方式,下面写一个例子介绍如何使用:


资源配置文件:

LocalStrings_fr.java:

package terry.codex;

import java.util.Collections;
import java.util.Enumeration;
import java.util.ResourceBundle;

/**
 * @编写人: yh.zeng
 * @编写时间:2017-12-3 下午4:58:26
 * @文件描述: LocalStrings法语配置文件
 */
public class LocalStrings_fr extends ResourceBundle{

	@Override
	protected Object handleGetObject(String key) {
		if(key.equals("tmpdir")){
			return "{0} itinéraires désignés avec moins";
		}
		return null;
	}

	@Override
	public Enumeration<String> getKeys() {
		 return Collections.enumeration(keySet());
	}
} 
LocalStrings_en.properties:

tmpdir=Cannot find specified temporary folder at {0}
LocalStrings_zh.properties:

tmpdir=\u5728{0}\u8def\u5f84\u4e0b\u627e\u4e0d\u5230\u6307\u5b9a\u7684\u6587\u4ef6\u5939
LocalStrings.properties:

tmpdir=\u5728{0}\u8def\u5f84\u4e0b\u627e\u4e0d\u5230\u6307\u5b9a\u7684\u6587\u4ef6\u5939

测试例子demo


ResourceBundleTest:

package terry.codex;

import java.io.File;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLClassLoader;
import java.text.MessageFormat;
import java.util.Locale;
import java.util.MissingResourceException;
import java.util.ResourceBundle;


/**
 * @编写人: yh.zeng
 * @编写时间:2017-12-3 上午12:35:42
 * @文件描述: 通过ResourceBundle的方式从资源文件(如messages.properties)中自动读取并进行资源绑定的demo
 *           可以用于实现国际化
 */
public class ResourceBundleTest {
	
	public static void main(String args[]){
        String bundleName = "terry.codex.LocalStrings";
        
        /**
         * 1、在当前类加载器下,找Java 虚拟机实例的当前默认语言环境值对应的配置文件,会找以下文件内容
         *        terry/codex/LocalStrings_zh.class
         *        terry/codex/LocalStrings_zh.properties
         *        terry/codex/LocalStrings.class
         *        terry/codex/LocalStrings.properties
         *    文件内容自上而下覆盖
         *    LocalStrings_zh.class文件会覆盖掉LocalStrings_zh.properties文件的内容
         *    LocalStrings_zh.properties文件会覆盖掉LocalStrings.class文件的内容
         *    LocalStrings.class文件会覆盖掉LocalStrings.properties文件的内容
         *    注意:LocalStrings_zh.class文件必须是ResourceBundle的子类,实现handleGetObject和getKeys方法!
         */
        try {
        	System.out.println("Example1:");
        	ResourceBundle bundle  = ResourceBundle.getBundle(bundleName);
            if(bundle != null){
            	String value = bundle.getString("tmpdir");
            	String params[] = new String[]{"D:\\TMP"};
                MessageFormat mf = new MessageFormat(value);
                System.out.println(mf.format(params, new StringBuffer(), null).toString());
            }
		} catch (MissingResourceException ex) {
			ex.printStackTrace();
		}

        
        
        /**
         * 2、Locale.ENGLISH在当前类加载器下找以下文件的内容:
         *       terry/codex/LocalStrings_en.class
         *       terry/codex/LocalStrings_en.properties
         *       terry/codex/LocalStrings.class
         *       terry/codex/LocalStrings.properties
         *    文件内容自上而下覆盖
         *    LocalStrings_en.class文件会覆盖掉LocalStrings_en.properties文件的内容
         *    LocalStrings_en.properties文件会覆盖掉LocalStrings.class文件的内容
         *    LocalStrings.class文件会覆盖掉LocalStrings.properties文件的内容
         *    注意:LocalStrings_en.class文件必须是ResourceBundle的子类,实现handleGetObject和getKeys方法!
         */
        try {
        	System.out.println("Example2:");
        	ResourceBundle bundle  = ResourceBundle.getBundle(bundleName, Locale.ENGLISH);
            if(bundle != null){
            	String value = bundle.getString("tmpdir");
            	String params[] = new String[]{"D:\\TMP"};
                MessageFormat mf = new MessageFormat(value);
                mf.setLocale(Locale.ENGLISH);
                System.out.println(mf.format(params, new StringBuffer(), null).toString());
            }
		} catch (MissingResourceException ex) {
			ex.printStackTrace();
		}
        
        
        /**
         * 3、在当前类加载器下找以下文件:
         *       terry/codex/LocalStrings_zh.class
         *       terry/codex/LocalStrings_zh.properties
         *       terry/codex/LocalStrings.class
         *       terry/codex/LocalStrings.properties
         *    文件内容自上而下覆盖
         *    LocalStrings_zh.class文件会覆盖掉LocalStrings_zh.properties文件的内容
         *    LocalStrings_zh.properties文件会覆盖掉LocalStrings.class文件的内容
         *    LocalStrings.class文件会覆盖掉LocalStrings.properties文件的内容
         *    注意:LocalStrings_zh.class文件必须是ResourceBundle的子类,实现handleGetObject和getKeys方法!
         */
        try {
        	System.out.println("Example3:");
        	ResourceBundle bundle  = ResourceBundle.getBundle(bundleName, Locale.CHINA);
            if(bundle != null){
            	String value = bundle.getString("tmpdir");
            	String params[] = new String[]{"D:\\TMP"};
                MessageFormat mf = new MessageFormat(value);
                mf.setLocale(Locale.CHINA);
                System.out.println(mf.format(params, new StringBuffer(), null).toString());
            }
		} catch (MissingResourceException ex) {
			ex.printStackTrace();
		}

   
        /**
         * 4、在当前类加载器下找以下文件:
         *       terry/codex/LocalStrings_fr.class
         *       terry/codex/LocalStrings_fr.properties
         *       terry/codex/LocalStrings.class
         *       terry/codex/LocalStrings.properties
         *    文件内容自上而下覆盖
         *    LocalStrings_fr.class文件会覆盖掉LocalStrings_fr.properties文件的内容
         *    LocalStrings_fr.properties文件会覆盖掉LocalStrings.class文件的内容
         *    LocalStrings.class文件会覆盖掉LocalStrings.properties文件的内容  
         *    注意:LocalStrings_fr.class文件必须是ResourceBundle的子类,实现handleGetObject和getKeys方法!
         */
        try {
        	System.out.println("Example4:");
        	ResourceBundle bundle  = ResourceBundle.getBundle(bundleName, Locale.FRANCE);
            if(bundle != null){
            	String value = bundle.getString("tmpdir");
            	String params[] = new String[]{"D:\\TMP"};
                MessageFormat mf = new MessageFormat(value);
                mf.setLocale(Locale.FRANCE);
                System.out.println(mf.format(params, new StringBuffer(), null).toString());
            }
		} catch (MissingResourceException ex) {
			ex.printStackTrace();
		}

        
        /**
         * 5、在D:\\loader这个类加载路径下找以下文件:
         *       terry/codex/LocalStrings_zh.class
         *       terry/codex/LocalStrings_zh.properties
         *       terry/codex/LocalStrings.class
         *       terry/codex/LocalStrings.properties
         *    文件内容自上而下覆盖
         *    LocalStrings_zh.class文件会覆盖掉LocalStrings_zh.properties文件的内容
         *    LocalStrings_zh.properties文件会覆盖掉LocalStrings.class文件的内容
         *    LocalStrings.class文件会覆盖掉LocalStrings.properties文件的内容
         *    注意:LocalStrings_zh.class文件必须是ResourceBundle的子类,实现handleGetObject和getKeys方法!
         */
		try {
			bundleName = "terry.codex2.LocalStrings";
			System.out.println("Example5:");
	        String fileUrlString = new File("D:\\loader").toURI().toString();
	        fileUrlString = fileUrlString.replaceAll("!/", "%21/");
			ClassLoader classLoader = new URLClassLoader(new URL[]{new URL(fileUrlString)});
	        if (classLoader != null) {
	            try {
	            	ResourceBundle bundle = ResourceBundle.getBundle(bundleName, Locale.CHINA, classLoader);
	                if(bundle != null){
	                	String value = bundle.getString("tmpdir");
	                	String params[] = new String[]{"D:\\TMP"};
	                    MessageFormat mf = new MessageFormat(value);
	                    mf.setLocale(Locale.CHINA);
	                    System.out.println(mf.format(params, new StringBuffer(), null).toString());
	                }
	            } catch (MissingResourceException ex2) {
	            	ex2.printStackTrace();
	            }
	        }
		} catch (MalformedURLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
	}
}

程序运行结果:

Example1:
在D:\TMP路径下找不到指定的文件夹
Example2:
Cannot find specified temporary folder at D:\TMP
Example3:
在D:\TMP路径下找不到指定的文件夹
Example4:
D:\TMP itinéraires désignés avec moins
Example5:
在D:\TMP路径下找不到指定的文件夹

demo:见 https://github.com/zengyh/CodeLibary/tree/master/src/resource/bundle/ResourceBundleTest.java


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值