关于Java中的*.properties的操作

只给出具体代码,觉得有用的可以参考一下


/**
 * 流处理工具类
 * @author Shmily
 */
public class StreamUtils {
	private static Logger logger = Logger.getLogger(StreamUtils.class);  
	/**
	 * 将配置文件*。properties直接转换为Java对象
	 * @param proPath 配置文件路径
	 * @return java.util.Properties or null
	 */
    public static Properties loadProperty(String proPath){
    	Properties temp=new Properties();
    	InputStream in= StreamUtils.class.getResourceAsStream(proPath);
    	try {
			temp.load(in);
			in.close();
			return temp;
		} catch (Exception e) {
			logger.warn("文件加载失败");
			return null;
		}
    }
    /**
     * 修改属性文件的值
     * @param proPath 属性文件的路径
     * @param key  
     * @param value
     * @return 是否修改成功
     */
    public static boolean updateProperty(String proPath,String key,String value){
    	Properties temp=loadProperty(proPath);
    	if(temp!=null){
    	    //修改值
    		temp.setProperty(key, value);
    		try {
    			File f=new File(String.class.getResource(proPath).toURI().getPath());
    			OutputStream out=new FileOutputStream(f);
    			//保存更新
				temp.store(out, "update");
				f=null;
				out.flush();
				out.close();
			} catch (Exception e) {
				logger.error("属性更新失败");
			} 
    		return true;
    	}else{
    		logger.error("文件加载失败");
    		return false;
    	}
    }
    /**
     * 删除特定key
     * @param proPath 属性文件的路径
     * @param key
     * @return 是否删除成功
     */
    public static boolean updateProperty(String proPath,String key){
    	Properties temp=loadProperty(proPath);
    	if(temp!=null){
    		temp.remove(key);
    		try {
    			FileOutputStream out=new FileOutputStream(new File(String.class.getResource(proPath).toURI().getPath()));
    			//保存更新
				temp.store(out, "update");
			    temp=null;
			    out.flush();
			    out.close();
    		} catch (Exception e) {
				logger.error("属性更新失败");
			} 
    		return true;
    	}else{
    		logger.error("文件加载失败");
    		return false;
    	}
    }
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值