您的位置:首页 > 运维架构

web项目实际部署中修改properties配置文件内容

2017-07-27 17:52 691 查看
web项目实际部署中修改properties配置文件内容:

1、修改properties文件中属性值对应的值,但其样式且顺序改变,且不保留注释信息

/**
* 修改properties文件中属性值对应的值
* 修改其样式且顺序改变
* @param propertiesName properties文件名称
* @param propertity 属性名称
* @param value 属性值
*/
public void updateProperties(String propertiesName, String propertity, String value){
Properties prop = new Properties();
try {
prop.load(TraceInterceptor.class.getResourceAsStream("/" + propertiesName));
prop.setProperty(propertity, value);
} catch (IOException e) {
//加载配置文件出错
e.printStackTrace();
}

String basePath = TraceInterceptor.class.getResource("/").getPath() + propertiesName;
OutputStream out;
try {
out = new FileOutputStream(basePath);
prop.store(out, null);
} catch (FileNotFoundException e) {
//配置文件未发现
e.printStackTrace();
} catch (IOException e) {
//配置文件内容写入出错
e.printStackTrace();
}
}


2、修改properties文件中属性值对应的值,保留其原样式

/**
* 修改properties文件中属性值对应的值
* 不修改其样式
* @param propertiesName properties文件名称
* @param propertity 属性名称
* @param value 属性值
*/
public void updateProperties(String propertiesName, String propertity, String value){

String basePath = this.getClass().getResource("/").getPath() + propertiesName;
FileReader fr = null;
BufferedReader bf = null;
StringBuffer buf = new StringBuffer();
try {
fr = new FileReader(basePath);
bf = new BufferedReader(fr);

String line = null;
while( (line = bf.readLine()) != null){
String cloneLine = line;
if(line.trim().indexOf("#", 0) == 0){
buf.append(cloneLine);
}else{
String property = cloneLine.trim().split("=")[0];
if(propertity.equals(property.trim())){
buf.append(property.trim() + " = " + value);
}else{
buf.append(cloneLine);
}
}
buf.append(System.getProperty("line.separator"));
}
} catch (IOException e) {
//文件读取失败
e.printStackTrace();
} finally{
if(bf != null){
try {
bf.close();
} catch (IOException e) {
//带缓冲的字符输入流关闭失败
e.printStackTrace();
}
}
}

FileWriter fw = null;
BufferedWriter bw = null;
try {
fw = new FileWriter(basePath);
bw = new BufferedWriter(fw);
bw.write(buf.toString());
} catch (IOException e) {
//字符输出流类创建失败
e.printStackTrace();
} finally {
if(bw != null){
try {
bw.close();
} catch (IOException e) {
//带缓冲的字符输出流关闭失败
e.printStackTrace();
}
}
}

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐