---
title: "将properties内容放置到map中"
author: "g21121"
date: "2012-05-24T14:37:44Z"
tags: []
categories: ["企业架构"]
slug: "properties-map"
draft: false
lastmod: "2012-05-24T14:38:31Z"
id: 1539703
url: "https://286.iteye.com/blog/1539703"
---

代码比较简单：

```
private static Map<Object, Object> map;
private static Properties p;

static {
	//读取properties文件
	InputStream is = XXX.class.getClassLoader().getResourceAsStream("xxx.properties");
	//创建资源文件实例
	p = new Properties();
	//根据情况初始化map实例
	if (map == null)
		map = new HashMap<Object, Object>();
	try {
		if (is != null) {
			//读取资源文件内容
			p.load(is);
			//循环将内容放置到map中
			for(Object name:p.keySet().toArray()){
				map.put(name, p.getProperty(name.toString()));
			}
		}
	} catch (IOException e) {
		e.printStackTrace();
	}
}

/**
 * 
 * 方法描述：获取id对应的值
 * 
 * @author liming
 * @time 2012-5-24 下午02:05:45
 * 
 * @param id
 * @return
 */
public static String getRedPath(String id) {
	return map.get(id).toString();
}
```

 

首先是读取资源文件，然后遍历出所以key值，我这里用的是set遍历，你也可以用：

```
		Enumeration e=p.elements();
				while(e.hasMoreElements()){
					String name=(String) e.nextElement();
					String value=p.getProperty(name);
				}
```

 这种方法遍历，效果是一样的。只要是取出key和value就可以一个一个放入map中了