java中利用ResourceBundle、MessageFormat格式化输出properties中的消息

下面是一个利用ResourceBundle、MessageFormat格式化输出properties中的消息的java代码:

package net.yedward.util.common;

import java.text.MessageFormat;
import java.util.ResourceBundle;

/**
 * MessageDemo
 * 
 * @author YEDWARD
 *
 */
public class MessageDemo {
	private static final String BUNDLE_NAME = "net.yedward.util.common.message";
	private static final ResourceBundle RESOURCE_BUNDLE = ResourceBundle.getBundle(BUNDLE_NAME);

	/**
	 * main方法
	 * 
	 * @param args
	 */
	public static void main(String[] args) {
		if (args.length == 0) {
			usage();
		}
		boolean test = true;
		if (test) {
			System.out.println(getString("Introduction", "yedward", "programmer"));
			System.out.println(getString("Greet"));
		}
	}

	/**
	 * usage
	 */
	private static void usage() {
		String lines = getString("Usage.Lines");
		for (int i = 0; i < Integer.parseInt(lines); i++) {
			System.out.println(getString("Usage." + i));
		}
	}

	/**
	 * 从properties获得指定建的值
	 * 
	 * @param key
	 * @return
	 */
	private static String getString(String key) {
		return RESOURCE_BUNDLE.getString(key);
	}

	/**
	 * 从properties获得指定键的值,并格式化输出
	 * 
	 * @param key
	 * @param param1
	 * @param param2
	 * @return
	 */
	private static String getString(String key, String param1, String param2) {
		return MessageFormat.format(RESOURCE_BUNDLE.getString(key), new Object[] { param1, param2 });
	}
}

message.properties中的内容如下:

Usage.Lines=5
Usage.0=This is just a property for testing, usages:
Usage.1=\   1. I don't know what can I do.
Usage.2=   2. I don't know what can I do.
Usage.3=   3. I don't know what can I do.
Usage.4=\   4. I don't know what can I do.

Introduction=My name is {0}, I am a {1}.
Greet=Nice to meet you!

上面的java代码运行结果如下图所示:

运行结果

图1:运行结果

从图1中可以看到,1.和4.前面有空格,而2.和3.前面没有,这是因为在properties文件中加了反斜杠(\),这是一个小细节。格式化输出的意思就是,讲properties中的{0}、{1}这种用具体的给定的值进行替换,然后输出替换后的信息。

本文标题:java中利用ResourceBundle、MessageFormat格式化输出properties中的消息

本文链接:http://yedward.net/?id=151

本文版权归作者所有,欢迎转载,转载请以文字链接的形式注明文章出处。

相关文章