java读取配置文件的工具类_java配置文件读取工具类

本文介绍了一个名为PropertyReader的Java类,用于读写配置文件,包括按键获取值、获取所有属性和批量写入。它简化了在src/user.properties文件中的操作,适合处理基础的配置管理任务。
摘要由CSDN通过智能技术生成

packageutils;importjava.io.BufferedInputStream;importjava.io.FileInputStream;importjava.io.FileOutputStream;importjava.io.IOException;importjava.io.InputStream;importjava.io.InputStreamReader;importjava.io.OutputStream;importjava.util.Enumeration;importjava.util.HashMap;importjava.util.List;importjava.util.Map;importjava.util.Properties;/*** 读写配置文件

* 路径格式 : src/user.properties

*@authorcyh

**/

public classPropertyReader {private static final String BASEPATH = "D:/java/";//根据Key读取Value

public staticString GetValueByKey(String filename, String key) {

Properties pps= newProperties();try{

InputStream in= new BufferedInputStream (new FileInputStream(BASEPATH+filename));

pps.load(in);

String value= pps.getProperty(key)+"";if(("null").equals(value)) {return null;

}

in.close();returnvalue;

}catch(IOException e) {//e.printStackTrace();

return null;

}

}//读取Properties的全部信息

public static MapGetAllProperties(String filename) {

Map map = new HashMap();try{

Properties pps= newProperties();

InputStream in= new BufferedInputStream(new FileInputStream(BASEPATH+filename));

pps.load(in);

Enumeration en= pps.propertyNames(); //得到配置文件的名字

while(en.hasMoreElements()) {

String strKey=(String) en.nextElement();

String strValue=pps.getProperty(strKey);

map.put(strKey, strValue);

}

}catch(IOException e) {//e.printStackTrace();

}returnmap;

}//写入Properties信息

public static void WriteProperties (String filename, String pKey, String pValue) throwsIOException {

Properties pps= newProperties();

InputStream in= new FileInputStream(BASEPATH+filename);//从输入流中读取属性列表(键和元素对)

pps.load(in);//调用 Hashtable 的方法 put。使用 getProperty 方法提供并行性。//强制要求为属性的键和值使用字符串。返回值是 Hashtable 调用 put 的结果。

OutputStream out = new FileOutputStream(BASEPATH+filename);

pps.setProperty(pKey, pValue);//以适合使用 load 方法加载到 Properties 表中的格式,//将此 Properties 表中的属性列表(键和元素对)写入输出流

pps.store(out, "Update " + pKey + " name");

out.flush();

in.close();

out.close();

}//批量写入Properties信息

public static void WritePropertiesBatch (String filename, List list, Map map) throwsIOException {

Properties pps= newProperties();

InputStream in= new FileInputStream(BASEPATH+filename);

InputStreamReader inputStreamReader= new InputStreamReader(in,"UTF-8");//从输入流中读取属性列表(键和元素对)

pps.load(inputStreamReader);

OutputStream out= new FileOutputStream(BASEPATH+filename);for(String str : list) {

pps.setProperty(str, map.get(str));

}

pps.store(out,"Update");

out.flush();

in.close();

out.close();

}

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值