properties文件读写操作

    随着项目的深入,为了便于项目的管理,某些常用的关键信息需要提取出来放在单独的配置文件,一般采用properties文件格式,这样当需要修改某项信息时,不会牵一发而动全身,大幅提高了程序可拓展性的同时,也节约了很多程序的开发与维护成本。

    看到网上很多帖子总结的不是很完善,于是小博耗费了一些时间,精心整合编写一套读写properties文件的工具类,并与各位分享。具体代码如下:

package com.web.utils;

import java.io.BufferedInputStream;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.URL;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;

import com.google.common.base.Throwables;
import com.google.common.collect.Maps;
import com.google.common.io.Resources;

/**
 * properties文件操作
 * 
 * @author jiangyf
 */
public class PropertiesUtil {
	private static Map<String, String> map = null;
	private static Properties props = new Properties();

	/**
	 * 加载配置文件
	 * 
	 * @param propPath
	 *            文件路径
	 * @return void
	 */
	public static void loadByPropPath(String propPath) {
		try {
			InputStream in = new FileInputStream(propPath);
			props.load(in);
			in.close();
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	/**
	 * 加载配置文件
	 * 
	 * @param propName
	 *            文件名
	 * @return void
	 */
	public static void loadByPropName(String propName) {
		try {
			InputStream in = ClassLoader.class.getResourceAsStream(propName);
			props.load(in);
			in.close();
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	/**
	 * 读取属性文件中相应键的值
	 * 
	 * @param key
	 *            主键
	 * @return String
	 */
	public static String getKeyValue(String key) {
		return props.getProperty(key);
	}

	/**
	 * 根据主键key读取主键的值value
	 * 
	 * @param propPath
	 *            属性文件路径
	 * @param key
	 *            键名
	 */
	public static String getKeyValue(String propPath, String key) {
		try {
			InputStream in = new BufferedInputStream(new FileInputStream(
					propPath));
			props.load(in);
			in.close();
			return props.getProperty(key);
		} catch (Exception e) {
			e.printStackTrace();
			return null;
		}
	}

	/**
	 * 获取配置文件信息
	 * 
	 * @param propName
	 * @return Map<String, String>
	 */
	public static Map<String, String> readProperties(String propName) {
		Properties properties = new Properties();
		URL resource = Resources.getResource(propName);
		try {
			InputStreamReader isr = new InputStreamReader(
					resource.openStream(), "UTF-8");
			properties.load(isr);
			isr.close();
		} catch (Exception e) {
			throw Throwables.propagate(e);
		}
		return Maps.fromProperties(properties);
	}

	/**
	 * 更新properties文件的键值对 如果该主键已经存在,更新该主键的值;如果该主键不存在,则插入一对键值。
	 * 
	 * @param map
	 *            键值对
	 */
	public static void writeProperties(Map<String, String> map, String propPath) {
		try {
			// 调用 Hashtable 的方法 put,使用 getProperty 方法提供并行性。
			// 强制要求为属性的键和值使用字符串。返回值是 Hashtable 调用 put 的结果。
			OutputStream fos = new FileOutputStream(propPath);
			for (Map.Entry<String, String> entry : map.entrySet()) {
				props.setProperty(entry.getKey(), entry.getValue());
			}
			// 以适合使用 load 方法加载到 Properties 表中的格式,
			// 将此 Properties 表中的属性列表(键和元素对)写入输出流
			props.store(fos, "");
			fos.close();

		} catch (IOException e) {
			System.err.println("属性文件更新错误");
		}
	}

	/**
	 * 更新properties文件的键值对 如果该主键已经存在,更新该主键的值;如果该主键不存在,则插入一对键值。
	 * 
	 * @param propPath
	 *            属性文件路径
	 * @param map
	 *            键值对
	 */
	public static void writeProperties(String propPath, Map<String, String> map) {
		try {
			// 调用 Hashtable 的方法 put,使用 getProperty 方法提供并行性。
			// 强制要求为属性的键和值使用字符串。返回值是 Hashtable 调用 put 的结果。
			loadByPropPath(propPath);
			OutputStream fos = new FileOutputStream(propPath);
			for (Map.Entry<String, String> entry : map.entrySet()) {
				props.setProperty(entry.getKey(), entry.getValue());
			}
			// 以适合使用 load 方法加载到 Properties 表中的格式,
			// 将此 Properties 表中的属性列表(键和元素对)写入输出流
			props.store(fos, "");
			fos.close();
		} catch (IOException e) {
			System.err.println("属性文件更新错误");
		}
	}

	/**
	 * 获取配置文件信息
	 * 
	 * @param propName
	 * @return Map<String, String>
	 */
	public static Map<String, String> propertiesToMap(String propName) {
		InputStream is = PropertiesUtil.class.getClassLoader()
				.getResourceAsStream(propName);
		Properties props = new Properties();
		if (map == null) {
			map = new HashMap<String, String>();
		}
		try {
			props.load(is);
			Enumeration<Object> en = props.keys();
			while (en.hasMoreElements()) {
				String key = en.nextElement().toString();
				String val = props.getProperty(key);
				map.put(key, val);
			}
			is.close();
		} catch (IOException e) {
			e.printStackTrace();
		}
		return map;
	}

	/**
	 * 获取配置文件信息
	 * 
	 * @param popName
	 * @param hashMap
	 * @return Map<String, String>
	 */
	public static Map<String, String> propertiesToMap(String propName,
			Map<String, String> hashMap) {
		map = hashMap;
		return readProperties(propName);
	}

//	public static void main(String[] args) {
//		Map<String, String> map2 = new HashMap<String, String>();
//		map2.put("key1", "value1");
//		map2.put("key2", "value2");
//		writeProperties(map2);
//	}

}

 

代码地址:https://github.com/github-jade/myweb/blob/develop/src/main/java/com/web/utils/PropertiesUtil.java

转载于:https://my.oschina.net/jiangyf/blog/804705

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值