读取.properties的内容,并将内容放入一个Map中

1. sql.properties

select_emp_by_id = select * from emp where empno = ?
select_emp_by_name = select * from emp where ename = ?

 

 

 

2. Constants.java

import java.util.HashMap;
import java.util.Map;

/**
 * @ClassName: Constants
 * @Description: 常量类
 * @author 
 * @date 2011-12-28
 * @version V1.0
 */
public final class Constants {

	private Constants() {
	}

	public static Map<String, String> loadSqlMap = new HashMap<String, String>(
			16);
	
	
}

 

3. 读取资源文件类

import java.io.IOException;
import java.io.InputStream;
import java.util.Iterator;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Properties;
import java.util.Set;

/**
 * @ClassName: LoadPopertiesFile
 * @Description: TODO
 * @author
 * @date 2011-12-28
 * @version V1.0
 */
public final class LoadPopertiesFile {

	private LoadPopertiesFile() {
	}

	/**
	 * @Title: loadSqlFile
	 * @Description: 加载sql.properties文件,并获取其中的内容(key-value)
	 * @param filePath
	 *            : 文件路径
	 * @author 
	 * @date 2011-12-28
	 */
	public static void loadSqlFile(String filePath) {

		if (null == filePath || "".equals(filePath.trim())) {
			System.out.println("The file path is null,return");
			return;
		}

		filePath = filePath.trim();

		// 获取资源文件
		InputStream is = LoadPopertiesFile.class.getClassLoader()
				.getResourceAsStream(filePath);

		// 属性列表
		Properties prop = new Properties();

		try {
			// 从输入流中读取属性列表
			prop.load(is);
		} catch (IOException e) {
			System.out.println("load file faile." + e);
			return;
		} catch (Exception e) {
			System.out.println("load file faile." + e);
			return;
		}

		// 返回Properties中包含的key-value的Set视图
		Set<Entry<Object, Object>> set = prop.entrySet();
		// 返回在此Set中的元素上进行迭代的迭代器
		Iterator<Map.Entry<Object, Object>> it = set.iterator();
		String key = null, value = null;
		// 循环取出key-value
		while (it.hasNext()) {

			Entry<Object, Object> entry = it.next();

			key = String.valueOf(entry.getKey());
			value = String.valueOf(entry.getValue());

			key = key == null ? key : key.trim().toUpperCase();
			value = value == null ? value : value.trim().toUpperCase();
			// 将key-value放入map中
			Constants.loadSqlMap.put(key, value);
		}
	}
}

  

 

 4. 测试 Junit4

@Test
	public void loadSqlFile() {
		String filePath = "sql.properties";		
		LoadPopertiesFile.loadSqlFile(filePath);		
		String sql = Constants.loadSqlMap.get("select_emp_by_id".toUpperCase());
		System.out.println("sql=" + sql);
	}

 

5. 测试结果

sql=SELECT * FROM EMP WHERE EMPNO = ?

 

 

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值