读写属性文件

package com.jetsum.util;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Properties;

/**
 * 该类用于配置文件的读写操作。
 * @author ShaoJiang
 *
 */
public class PropertiesUtil {
	
	/**
	 * Properties对象
	 */
	public static Properties pros = null;
	
	static{
		pros = new Properties();
	}
	
	/**
	 * 通过路径加载配置文件,文件路径可以是绝对路径也可以是相对于class文件的路径。
	 * @param filePath 文件路径
	 */
	public static void load(String filePath){
        try {
        	InputStream in = filePath.contains(":")?new FileInputStream(filePath):PropertiesUtil.class.getResourceAsStream(filePath);
			pros.load(in);
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	
	/**
	 * 从文件加载属性值
	 * @param filePath 文件路径
	 * @param key 属性键值
	 * @return 返回属性值
	 */
	public static String loadValue(String filePath,String key){
		load(filePath);
		return get(key);
	}	

	/**
	 * 获得配置文件属性值
	 * @param key
	 * @return 返回属性值
	 */
	public static String get(String key){
		return pros.getProperty(key);
	}
	
	/**
	 * 保存配置文件
	 * @param filePath 文件路径
	 * @param comments 属性列表的描述
	 * @return 返回保存成功状态
	 */
	public static boolean store(String filePath,String comments){
		try {
			OutputStream out = new FileOutputStream(filePath.contains(":")?filePath:PropertiesUtil.class.getResource(filePath).getFile());
			pros.store(out,comments);
			return true;
		} catch (FileNotFoundException e) {
			e.printStackTrace();
			return false;
		} catch (IOException e) {
			e.printStackTrace();
			return false;
		}
	}
	
	/**
	 * 保存配置文件
	 * @param filePath 文件路径
	 * @return 返回保存成功状态
	 */
	public static boolean store(String filePath){
		return store(filePath,"update:"+filePath);
	}
	
	/**
	 * 设置配置文件属性
	 * @param key 配置key
	 * @param value 配置value
	 */
	public static void set(String key,String value){
		pros.setProperty(key, value);
	}
	
	/**
	 * 设置配置文件属性
	 * @param filePath 文件路径
	 * @param key 配置key
	 * @param value 配置value
	 * @return 返回保存成功状态
	 */
	public static boolean storeValue(String filePath,String key,String value){
		load(filePath);
		pros.setProperty(key, value);
		return store(filePath);
	}
	
	/**
	 * 打印属性列表
	 */
	public static void printPropertieList(){		
		pros.list(System.out);
	}
}

 

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

sjiang

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

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

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

打赏作者

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

抵扣说明:

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

余额充值