您好,欢迎来到花图问答。
搜索
您的当前位置:首页java读写Properties属性文件公用方法

java读写Properties属性文件公用方法

来源:花图问答
java读写Properties属性文件公用方法

在Java中有个比较重要的类Properties(Java.util.Properties),主要用于读取Java的配置文件,各种语言都有自己所支持的配置文件,配置文件中很多变量是经常改变的,这样做也是为了方便用户,让用户能够脱离程序本身去修改相关的变量设置。在Java中,其配置文件常为.properties文件,格式为文本文件,文件的内容的格式是“键=值”的格式,文本注释信息可以用\"#\"来注释。

Properties提供了如下几个主要的方法:

1. getProperty ( String key),用指定的键在此属性列表中搜索属性。也就是通过参数 key ,得到 key 所对应的 value。

2. load ( InputStream inStream),从输入流中读取属性列表(键和元素对)。通过对指定的文件(如test.properties 文件)进行装载来获取该文件中的所有键 - 值对。以供 getProperty ( String key) 来搜索。

3. setProperty ( String key, String value) ,调用 Hashtable 的方法 put 。他通过调用基类的put方法来设置 键 - 值对。

4. store ( OutputStream out, String comments),以适合使用 load 方法加载到 Properties 表中的格式,将此 Properties 表中的属性列表(键和元素对)写入输出流。与 load 方法相反,该方法将键 - 值对写入到指定的文件中去。 5. clear (),清除所有装载的 键 - 值对。该方法在基类中提供。

以下提供一套读写配置文件的公用实用方法,我们以后可以在项目中进行引入。

import java.io.BufferedInputStream; import java.io.FileInputStream; import java.io.FileOutputStream;

import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.util.Enumeration; import java.util.Properties; import org.apache.log4j.Logger;

public class PropertieUtil { //设置日志

private static Logger logger=Logger.getLogger(PropertieUtil.class);

private PropertieUtil() { } /**

* 读取配置文件某属性 */

public static String readValue(String filePath,String key) { } /**

* 打印配置文件全部内容 */

public static void readProperties(String filePath) {

Properties props=new Properties(); try {

Properties props=new Properties(); try { }

if(filePath.startsWith(\"/\")) { }

InputStream in=PropertieUtil.class.getResourceAsStream(filePath); props.load(in);

String value=props.getProperty(key); return value;

// TODO Auto-generated catch block return null;

filePath=\"/\"+filePath;

} catch (IOException e) {

logger.error(e);

}

if(!filePath.startsWith(\"/\")) { }

InputStream in=PropertieUtil.class.getResourceAsStream(filePath); props.load(in);

Enumeration en=props.propertyNames(); //遍历打印

while(en.hasMoreElements()) { }

String key=(String)en.nextElement(); String property=props.getProperty(key); //日志信息显示键和值

logger.info(key+\":\"+property);

filePath=\"/\"+filePath;

}catch(Exception e) { }

//日志显示错误信息 logger.error(e);

最后测试效果如下:

调用:readProperties(\"jdbc.properties\");

调用writeProperties(\"test.properties\",\"test\",\"test\");

因篇幅问题不能全部显示,请点此查看更多更全内容

Copyright © 2019- huatuowenda.com 版权所有 湘ICP备2023022495号-1

违法及侵权请联系:TEL:199 1889 7713 E-MAIL:2724546146@qq.com

本站由北京市万商天勤律师事务所王兴未律师提供法律服务