前几天开发时遇到一个问题,在后台读取配置文件的时候无法读取属性值,于是上网查了查,现在在这分享给大家,
先附上代码吧:
包com.shafei.util;
进口java.io.bufferedinputstream中;
进口java.io.fileinputstream中;
进口java.io.fileoutputstream中;
进口的java.io.inputstream;
进口java.io.outputstream中;
进口的java.util.enumeration;
进口java.util.properties;
进口org.apache.log4j.logger;
公共类propertieutil {
私有静态记录器记录= logger.getlogger(propertieutil.class);
私人propertieutil(){
}
/ **
*读取配置文件某属性
* /
公共静态字符串readvalue(字符串文件路径,字符串键){
属性道具=新特性();
尝试{
//注意路径以/开始,没有则处理
如果(filepath.startswith(“/”)!)
文件路径=“/”+文件路径;
inputstream的时间= propertieutil.class.getresourceasstream(文件路径);
props.load(在);
字符串值= props.getproperty(键);
返回值;
}赶上(例外五){
logger.error(e);
返回null;
}
}
/ **
*打印配置文件全部内容(文件路径,配置文件名,如果有路径,道具/ test.properties)
* /
公共静态无效readproperties(字符串文件路径){
属性道具=新特性();
尝试{
//注意路径以/开始,没有则处理
如果(filepath.startswith(“/”)!)
文件路径=“/”+文件路径;
inputstream的时间= propertieutil.class.getresourceasstream(文件路径);
props.load(在);
枚举en = props.propertynames();
//遍历打印
的同时(en.hasmoreelements()){
字符串键=(字符串)en.nextelement();
string属性= props.getproperty(键);
的system.out.println(物业);
logger.info(键+“:”+物业);
}
}赶上(例外五){
logger.error(e);
}
}
/ **
*将值写入配置文件
* /
公共静态无效writeproperties(字符串文件名,字符串参数名称,字符串的parametervalue)抛出异常{
//本地测试特别注意,如果是maven的项目,请到\目标目录下查看文件,而不是源代码下
//注意路径不能加/了,加了则移除掉
,如果(filename.startswith(“/”))
filename.substring(1);
字符串文件路径= propertieutil.class.getresource(“/”)的getpath()+文件名。
//获取配置文件
属性pps =新特性();
在的inputstream =新的bufferedinputstream(新的fileinputstream(文件路径));
pps.load(在);
附寄();
出的outputstream =新的fileoutputstream(文件路径);
//设置配置名称和值
pps.setproperty(参数名称,的parametervalue);
//注释配置等于文件的注释
pps.store(满分,“更新”+参数名称+“名”);
了out.flush();
out.close();
}
公共静态无效的主要(字串[] args)抛出异常{
readproperties(“jdbc.properties”);
logger.info(readvalue(“jdbc.properties”,“javablog_write_url”));
// writeproperties(“conf / test.properties”,“datasource.driver”,“测试”);
readproperties(“conf / test.properties”);
}
}
上面的代码我也是学习大牛们的,也不是很难,很实用,希望对大家有帮助!
Copyright 2014-2024 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号