---
title: "Java 常用API的运用，效率及技巧八"
author: "wangchen.ily"
date: "2011-12-31T09:06:12Z"
tags: []
categories: ["开源软件"]
slug: "java-api"
draft: false
lastmod: "2011-12-30T10:47:05Z"
id: 1330021
url: "https://ily.iteye.com/blog/1330021"
---

## 8．ResourceBundle, Properties

**ResourceBundle：**开发一个项目， 配置文件是少不了的， 一些需要根据环境进行修改的参数， 都有得放到配置文件中去， 在Java中一般是通过一个properties文件来实现的， 这个文件以properties结尾。 内部结构是二维的， 以key=value的形式存在。 如下：

options.column.name.case=1

options.column.bean.serializable=1

options.column.bean.defaultconstructor=1

options.column.method.setter=1

options.general.user.version=1.0

database.connection\[0]=csc/csc@localhost\_oci8

database.connection\[1]=cscweb/cscweb@localhost\_thin

 

ResourceBundle用来解析这样的文件， 它的功能是可以根据你的Locale来进行解析配置文件， 如果一个产品需要进行多语言支持， 比如在不同语种的系统上， 会显示根据它的语言显示相应的界面语言， 就可以定义多份的properties文件， 每个文件的key是一样的， 只是value不一样， 然后在application起动的时候， 可以判别本机的Locale来解析相应的properties文件。 Properties文件里面的数据得要是Unicode。 在jdk下面可以用native2ascii这个命令进行转换。 例： native2ascii Message.txt Message.properties 会生成一个Unicode的文件。

 

**Properties:** Properties这个类其实就是从Hashtable继承下来的， 也就是说它是一个散列表， 区别在于它的key与value都是String型的， 另外也加了几个常用的方法：

Ø  String getProperty(String key)  取得一个property

Ø  String getProperty(String key, String defaultValue)  取property， 如果不存在则返回defaultValue。

Ø  void list(PrintStream out)  向out输出所有的properties

Ø  void list(PrintWriter out)

Ø  Enumeration propertyNames()  将所有的property key名以Enumeration形式返回。

Ø  Object setProperty(String key, String value) 设置一个property。

 

ResourceBundle与Properties一般结合起来使用。 它们的用法很简单， 由ResourceBundle解析出来的key与value然后放至到一个静态的Properties成员变量里面去， 然后就可以通过访问Properties的方法进行读取Property。 下面给个简单的例子：

 

```
public class PropertyManager implements Serializable {
	
	/** 定义一个静态的Properties变量 */
	private static Properties properties = new Properties();
	
	/**
	 * 通过一个类似于类名的参数进行Property文件的初期化
	 * 比如现在有一个文件叫Message.properties， 它存放在
	 * ejb/util下面并且， 这个目录在运行的classpath下面
	 * 则in就为ejb.util.Message
	 *
	 */
	public static void init(String in) throws MissingResourceException {
	    ResourceBundle bundle = ResourceBundle.getBundle(in);
	    Enumeration enum = bundle.getKeys();
	    Object key = null;
	    Object value = null;
	    while (enum.hasMoreElements()) {
	        key = enum.nextElement();
	        value = bundle.getString(key.toString());
	        properties.put(key, value);
	    }
	}
	
	/**
	 * 取得一个Property值
	 */
	public static String getProperty(String key) {
		return properties.get(key);
	}
	
	/**
	 * 设置一个Property值
	 */
	public static void setProperty(String key, String value) {
		properties.put(key, value);
	}
}
```

 

不过现在的Java产品中，越来越倾向于用XML替换Properties文件来进行配置。 XML配置具有层次结构清楚的优点。