新鲜出炉的操作java属性文件工具类

写在前面:
在Java开发中,我们经常会用到属性配置文件。比如,我们需要一个全局变量,这个变量又有可能经常变化,如果我们把它定义在程序中的话,那修改这个变量我们就得重新编译发布,尤其是当程序已经部署运行的话,这将带来很大麻烦。其实属性配置文件的应用场景还有很多,在java开发中可以说是无处不在。下面偶就给出一个操作属性资源文件的工具类。通过这个工具类,我们可以实现对属性配置文件的增删查的操作。

package com.yinhai.paysystem.hospital.base.utils;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.util.Properties;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

/**
* @name PropertiesUtil
* @title 操作属性文件工具类
* @desc
* @author 熊春
* @version 两定支付系统-V5.0 2008-06-16
*/
public class PropertiesUtil {
private static Log log = LogFactory.getLog(PropertiesUtil.class);//日志输出对象
private static String filePath;
private Properties objProperties; //属性对象

/**
* @name PropertiesUtil
* @title 构造函数
* @desc 加载属性资源文件
* @param String,boolean
* @return
* @throws Exception
*/
public PropertiesUtil(String filePath) throws Exception {
this.filePath = filePath;
File file = new File(filePath);
FileInputStream inStream = new FileInputStream(file);
try{
objProperties = new Properties();
objProperties.load(inStream);
}
catch(FileNotFoundException e){
log.error("未找到属性资源文件!");
e.printStackTrace();
throw e;
}
catch(Exception e){
log.error("读取属性资源文件发生未知错误!");
e.printStackTrace();
throw e;
}finally{
inStream.close();
}
}

/**
* @name savefile
* @title 持久化属性文件
* @desc 使用setValue()方法后,必须调用此方法才能将属性持久化到存储文件中
* @param String, String
* @return
* @throws Exception
*/
public void savefile(String desc) throws Exception{
FileOutputStream outStream = null;
try{
File file = new File(filePath);
outStream = new FileOutputStream(file);
objProperties.store(outStream, desc);//保存属性文件
}catch(Exception e){
log.error("保存属性文件出错.");
e.printStackTrace();
throw e;
}finally{
outStream.close();
}

}

/**
* @name getVlue
* @title 获取属性值
* @desc 指定Key值,获取value
* @param String
* @return String
*/
public String getValue(String key){
return objProperties.getProperty(key);
}

/**
* @name getVlue
* @title 获取属性值,支持缺省设置
* @desc 重载getValue()方法;指定Key值,获取value并支持缺省值
* @param String
* @return String
*/
public String getValue(String key, String defaultValue){
return objProperties.getProperty(key, defaultValue);
}

/**
* @name removeVlue
* @title 删除属性
* @desc 根据Key,删除属性
* @param String
* @return
*/
public void removeValue(String key){
objProperties.remove(key);
}

/**
* @name setValue
* @title 设置属性
* @desc
* @param String,String
* @return
*/
public void setValue(String key, String value){
objProperties.setProperty(key, value);
}

/**
* @name printAllVlue
* @title 打印所有属性值
* @desc
* @param
* @return
*/
public void printAllVlue(){
objProperties.list(System.out);
}
}
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值