java properties工具类_properties文件读写工具类PropertiesUtil.java

该博客介绍了一个Java PropertiesUtil工具类,用于读取和写入配置文件。类中包含读取指定key的值、获取全部配置信息以及更新key-value的方法。示例代码展示了如何使用该工具类操作'sysConfig.properties'文件。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

importjava.io.FileInputStream;importjava.io.FileOutputStream;importjava.io.IOException;importjava.io.InputStream;importjava.io.OutputStream;importjava.util.Properties;/***

*@author**/

public classPropertiesUtil {private String properiesName = "";publicPropertiesUtil() {

}publicPropertiesUtil(String fileName) {this.properiesName =fileName;

}/*** 按key获取值

*@paramkey

*@return

*/

publicString readProperty(String key) {

String value= "";

InputStream is= null;try{

is= PropertiesUtil.class.getClassLoader().getResourceAsStream(properiesName);

Properties p= newProperties();

p.load(is);

value=p.getProperty(key);

}catch(IOException e) {

e.printStackTrace();

}finally{try{

is.close();

}catch(IOException e) {

e.printStackTrace();

}

}returnvalue;

}/*** 获取整个配置信息

*@return

*/

publicProperties getProperties() {

Properties p= newProperties();

InputStream is= null;try{

is= PropertiesUtil.class.getClassLoader().getResourceAsStream(properiesName);

p.load(is);

}catch(IOException e) {

e.printStackTrace();

}finally{try{

is.close();

}catch(IOException e) {

e.printStackTrace();

}

}returnp;

}/*** key-value写入配置文件

*@paramkey

*@paramvalue*/

public voidwriteProperty(String key, String value) {

InputStream is= null;

OutputStream os= null;

Properties p= newProperties();try{

is= newFileInputStream(properiesName);//is = PropertiesUtil.class.getClassLoader().getResourceAsStream(properiesName);

p.load(is);//os = new FileOutputStream(PropertiesUtil.class.getClassLoader().getResource(properiesName).getFile());

os = newFileOutputStream(properiesName);

p.setProperty(key, value);

p.store(os, key);

os.flush();

os.close();

}catch(Exception e) {

e.printStackTrace();

}finally{try{if (null !=is)

is.close();if (null !=os)

os.close();

}catch(IOException e) {

e.printStackTrace();

}

}

}public static voidmain(String[] args) {//sysConfig.properties(配置文件)

PropertiesUtil p = new PropertiesUtil("sysConfig.properties");

System.out.println(p.getProperties().get("db.url"));

System.out.println(p.readProperty("db.url"));

PropertiesUtil q= new PropertiesUtil("resources/sysConfig.properties");

q.writeProperty("myUtils", "wang");

System.exit(0);

}

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值