欢迎来到天天文库
浏览记录
ID:55270316
大小:43.00 KB
页数:4页
时间:2020-05-08
《java读写Properties属性文件公用方法.doc》由会员上传分享,免费在线阅读,更多相关内容在教育资源-天天文库。
1、java读写Properties属性文件公用方法在Java中有个比较重要的类Properties(Java.util.Properties),主要用于读取Java的配置文件,各种语言都有自己所支持的配置文件,配置文件中很多变量是经常改变的,这样做也是为了方便用户,让用户能够脱离程序本身去修改相关的变量设置。在Java中,其配置文件常为.properties文件,格式为文本文件,文件的内容的格式是“键=值”的格式,文本注释信息可以用"#"来注释。Properties提供了如下几个主要的方法:1.getProperty(Stringkey),用指定的键在此属性列表中搜索属性。也就
2、是通过参数key,得到key所对应的value。2.load(InputStreaminStream),从输入流中读取属性列表(键和元素对)。通过对指定的文件(如test.properties文件)进行装载来获取该文件中的所有键-值对。以供getProperty(Stringkey)来搜索。3.setProperty(Stringkey,Stringvalue),调用Hashtable的方法put。他通过调用基类的put方法来设置键-值对。4.store(OutputStreamout,Stringcomments),以适合使用load方法加载到Properties表中的格式
3、,将此Properties表中的属性列表(键和元素对)写入输出流。与load方法相反,该方法将键-值对写入到指定的文件中去。5.clear(),清除所有装载的键-值对。该方法在基类中提供。以下提供一套读写配置文件的公用实用方法,我们以后可以在项目中进行引入。importjava.io.BufferedInputStream;importjava.io.FileInputStream;importjava.io.FileOutputStream;importjava.io.IOException;importjava.io.InputStream;importjava.io.O
4、utputStream;importjava.util.Enumeration;importjava.util.Properties;importorg.apache.log4j.Logger;publicclassPropertieUtil{//设置日志privatestaticLoggerlogger=Logger.getLogger(PropertieUtil.class);privatePropertieUtil(){}/***读取配置文件某属性*/publicstaticStringreadValue(StringfilePath,Stringkey){Proper
5、tiesprops=newProperties();try{if(filePath.startsWith("/")){filePath="/"+filePath;}InputStreamin=PropertieUtil.class.getResourceAsStream(filePath);props.load(in);Stringvalue=props.getProperty(key);returnvalue;}catch(IOExceptione){//TODOAuto-generatedcatchblocklogger.error(e);returnnull;}}/**
6、*打印配置文件全部内容*/publicstaticvoidreadProperties(StringfilePath){Propertiesprops=newProperties();try{if(!filePath.startsWith("/")){filePath="/"+filePath;}InputStreamin=PropertieUtil.class.getResourceAsStream(filePath);props.load(in);Enumeration>en=props.propertyNames();//遍历打印while(en.hasMoreEl
7、ements()){Stringkey=(String)en.nextElement();Stringproperty=props.getProperty(key);//日志信息显示键和值logger.info(key+":"+property);}}catch(Exceptione){//日志显示错误信息logger.error(e);}}最后测试效果如下:调用:readProperties("jdbc.properties");调用writeProperties("test.properties",
此文档下载收益归作者所有