package cn.hmsoft.application.config;

import java.io.File;
import java.io.FileReader;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;

import cn.hmsoft.exception.AppException;
import cn.hmsoft.exception.io.FileNotExistsException;

/******************
 * 配置文件辅助类
 * 
 * @author zxq
 * @create 2019-05-06 08:26:19
 * @version 2.0.0
 * @email: revisit@126.com
 * @Company: www.hmsoft.cn
 */
public class ConfigHelper {

	public static Map<String, String> loadProperites(String fileName) {
		Map<String, String> map = new HashMap<String, String>();
		File file = new File(fileName);
		if (!file.exists())
			throw new FileNotExistsException(file);
		if (file.isFile()) {
			loadProperites(file, map);
		} else {
			// 遍历获取
			for (File f : file.listFiles()) {
				// 只获取properties结尾的文件
				if (f.getName().toLowerCase().endsWith(".properties"))
					loadProperites(file, map);
			}
		}
		return map;
	}

	private static void loadProperites(File file, Map<String, String> map) {
		Properties prop = new Properties();
		if (!file.exists())
			throw new FileNotExistsException(file);
		try {
			prop.load(new FileReader(file));
			for (Object key : prop.keySet()) {
				map.put(key.toString().trim(), prop.get(key).toString().trim());
			}
		} catch (Exception e) {
			throw new AppException("initialize [" + file.getName() + "] config file error");
		}
	}
}
