浏览 2785 次
锁定老帖子 主题:新鲜出炉的操作java属性文件工具类
精华帖 (0) :: 良好帖 (0) :: 新手帖 (0) :: 隐藏帖 (0)
|
|
---|---|
作者 | 正文 |
发表时间:2008-06-17
在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); } } 声明:ITeye文章版权属于作者,受法律保护。没有作者书面许可不得转载。
推荐链接
|
|
返回顶楼 | |