[Java 常用类库]:PropUtils 属性文件类

Java读取和修改properties文件


方法说明:

1.Properties getProperties(String filepath):根据路径读取属性文件,返回Properties类;

2.void SaveProperties(Properties prop,String filepath):保存属性到指定路径(如果文件不存在,请先创建File);

3.String getConfigValue(String key):获取指定Key的属性;

4.void setConfigValue(String key,String value):设置指定Key的属性值。


其中方法3,4调用的属性文件为默认的文件,文件名和路径通过CONFIG和LOCATION设置,该文件的位置为工程中的src下导出jar文件的同级目录下LOCATION获取)。


下面代码:

public class PropUtils {
	public static String LOCATION;
	
	public static final String CONFIG = "config.properties";
	
	static{
		try {
			String temp = URLDecoder.decode(PropUtils.class.getProtectionDomain().getCodeSource().getLocation().getFile(), "UTF-8");
			LOCATION = temp.substring(1, temp.lastIndexOf('/'));
		} catch (UnsupportedEncodingException e) {
			LOCATION = "";
		}
		
	}
	/**
	 * @param args
	 * @throws Exception 
	 */
	public static Properties getProperties(String filepath) throws Exception {
		Properties prop = new Properties();
		FileInputStream fis = new FileInputStream(LOCATION+"/"+filepath);
		prop.load(fis);
		return prop;
	}
	
	public static void SaveProperties(Properties prop,String filepath) throws Exception {
		FileOutputStream fos = new FileOutputStream(LOCATION+"/"+filepath);
		prop.store(fos, "@author Isea533");
		fos.close();
	}

	public static String getConfigValue(String key) {
		try {
			Properties properties = getProperties(CONFIG);
			if(properties.get(key)!=null){
				return properties.get(key).toString();
			}
		} catch (Exception e) {
			System.out.println(e.getMessage());
		}
		return "";
	}
	
	public static void setConfigValue(String key,String value){
		try {
			Properties properties = getProperties(CONFIG);
			properties.setProperty(key, value);
			SaveProperties(properties, CONFIG);
		} catch (Exception e) {
			System.out.println(e.getMessage());
		}
	}
}





评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

isea533

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

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

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

打赏作者

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

抵扣说明:

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

余额充值