PropUtil 工具类

mport org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.*;
import java.net.URL;
import java.util.Properties;


public class PropUtil {
    private static Logger logger = LoggerFactory.getLogger(PropUtil.class);

    /**
     * load prop
     *
     * @param propertyFileName disk path when start with "file:", other classpath
     * @return
     */
    public static Properties loadProp(String propertyFileName) {
        InputStream in = null;
        try {
            // load file location, disk
            File file = new File(propertyFileName);
            if (!file.exists()) {
                return null;
            }
            URL url = new File(propertyFileName).toURI().toURL();
            in = new FileInputStream(url.getPath());
            if (in == null) {
                return null;
            }

            Properties prop = new Properties();
            prop.load(new InputStreamReader(in, "utf-8"));

            return prop;
        } catch (IOException e) {
            logger.error(e.getMessage(), e);
        } finally {
            if (in != null) {
                try {
                    in.close();
                } catch (IOException e) {
                    logger.error(e.getMessage(), e);
                }
            }
        }
        return null;
    }

    /**
     * write prop to disk
     *
     * @param properties
     * @param filePathName
     * @return
     */
    public static boolean writeProp(Properties properties, String filePathName){
        FileOutputStream fileOutputStream = null;
        try {

            // mk file
            File file = new File(filePathName);
            if (!file.exists()) {
                file.getParentFile().mkdirs();
            }

            // write data
            fileOutputStream = new FileOutputStream(file, false);
            properties.store(new OutputStreamWriter(fileOutputStream, "utf-8"), null);
            //properties.store(new FileWriter(filePathName), null);
            return true;
        } catch (IOException e) {
            logger.error(e.getMessage(), e);
            return false;
        } finally {
            if (fileOutputStream != null) {
                try {
                    fileOutputStream.close();
                } catch (IOException e) {
                    logger.error(e.getMessage(), e);
                }
            }
        }
    }

	/**
	 * 工具方法: 将指定路径的properties配置文件读取到Map中 
	 * 
	 * @param propertiesPath 配置文件地址
	 * @return 一个Map
	 */
	public static Map<String, String> readPropToMap(String propertiesPath) {
		Map<String, String> map = new HashMap<String, String>(16);
		try {
			InputStream is = SaTokenConfigFactory.class.getClassLoader().getResourceAsStream(propertiesPath);
			if (is == null) {
				return null;
			}
			Properties prop = new Properties();
			prop.load(is);
			for (String key : prop.stringPropertyNames()) {
				map.put(key, prop.getProperty(key));
			}
		} catch (IOException e) {
			throw new RuntimeException("配置文件(" + propertiesPath + ")加载失败", e);
		}
		return map;
	}
/**
	 * 工具方法: 将 Map 的值映射到一个 Model 上 
	 * 
	 * @param map 属性集合
	 * @param obj 对象, 或类型
	 * @return 返回实例化后的对象
	 */
	public static Object initPropByMap(Map<String, String> map, Object obj) {

		if (map == null) {
			map = new HashMap<String, String>(16);
		}

		// 1、取出类型
		Class<?> cs = null;
		if (obj instanceof Class) {
			// 如果是一个类型,则将obj=null,以便完成静态属性反射赋值
			cs = (Class<?>) obj;
			obj = null;
		} else {
			// 如果是一个对象,则取出其类型
			cs = obj.getClass();
		}

		// 2、遍历类型属性,反射赋值
		for (Field field : cs.getDeclaredFields()) {
			String value = map.get(field.getName());
			if (value == null) {
				// 如果为空代表没有配置此项
				continue;
			}
			try {
				Object valueConvert = getObjectByClass(value, field.getType());
				field.setAccessible(true);
				field.set(obj, valueConvert);
			} catch (IllegalArgumentException | IllegalAccessException e) {
				throw new RuntimeException("属性赋值出错:" + field.getName(), e);
			}
		}
		return obj;
	}


	/**
	 * 工具方法: 将字符串转化为指定数据类型 
	 * 
	 * @param str 值
	 * @param cs  要转换的类型
	 * @return 转化好的结果
	 */
	@SuppressWarnings("unchecked")
	private static <T> T getObjectByClass(String str, Class<T> cs) {
		Object value;
		if (str == null) {
			value = null;
		} else if (cs.equals(String.class)) {
			value = str;
		} else if (cs.equals(int.class) || cs.equals(Integer.class)) {
			value = Integer.valueOf(str);
		} else if (cs.equals(long.class) || cs.equals(Long.class)) {
			value = Long.valueOf(str);
		} else if (cs.equals(short.class) || cs.equals(Short.class)) {
			value = Short.valueOf(str);
		} else if (cs.equals(float.class) || cs.equals(Float.class)) {
			value = Float.valueOf(str);
		} else if (cs.equals(double.class) || cs.equals(Double.class)) {
			value = Double.valueOf(str);
		} else if (cs.equals(boolean.class) || cs.equals(Boolean.class)) {
			value = Boolean.valueOf(str);
		} else {
			throw new RuntimeException("未能将值:" + str + ",转换类型为:" + cs, null);
		}
		return (T) value;
	}


}

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

没事搞点事做serendipity

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值