java 修改配置文件_java web工程读取及修改配置文件

package com.bobo.util;

import java.io.BufferedReader;

import java.io.BufferedWriter;

import java.io.FileNotFoundException;

import java.io.FileOutputStream;

import java.io.IOException;

import java.io.InputStream;

import java.io.InputStreamReader;

import java.io.OutputStream;

import java.io.OutputStreamWriter;

import java.util.HashMap;

import java.util.Properties;public classPropertiesUtil {/**

* @param args*/

public static voidmain(String[] args) {

String fileName= "test.properties";

PropertiesUtil pu= newPropertiesUtil();

HashMap map=newHashMap();

map.put("age", "24");

map.put("name", "leishao");

pu.updateProperty(fileName, map);

System.out.println(pu.loadAllProperties(fileName));

System.out.println(pu.loadProperty(fileName, "name"));

}public HashMaploadAllProperties(String fileName) {

InputStreamis = PropertiesUtil.class.getClassLoader()

.getResourceAsStream(fileName);

BufferedReader br= new BufferedReader(new InputStreamReader(is));

Properties pr= newProperties();try{

pr.load(br);

HashMap hm = new HashMap();for(Object s : pr.keySet()) {

hm.put(s+ "", pr.getProperty(s + ""));

}returnhm;

}catch(IOException e) {//TODO Auto-generated catch block

e.printStackTrace();

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

br.close();

}catch(IOException e) {//TODO Auto-generated catch block

e.printStackTrace();

}

}

}return null;

}publicString loadProperty(String fileName, String key) {

InputStreamis = PropertiesUtil.class.getClassLoader()

.getResourceAsStream(fileName);

BufferedReader br= new BufferedReader(new InputStreamReader(is));

Properties pr= newProperties();try{

pr.load(br);if(pr.containsKey(key)) {return pr.get(key) + "";

}

}catch(IOException e) {//TODO Auto-generated catch block

e.printStackTrace();

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

br.close();

}catch(IOException e) {//TODO Auto-generated catch block

e.printStackTrace();

}

}

}return null;

}public void updateProperty(String fileName, HashMapmap) {

InputStreamis = PropertiesUtil.class.getClassLoader()

.getResourceAsStream(fileName);

BufferedReader br= new BufferedReader(new InputStreamReader(is));

Properties pr= newProperties();

String filePath=PropertiesUtil.class.getClassLoader().getResource(fileName).getFile();try{

pr.load(br);

pr.putAll(map);

OutputStreamout=newFileOutputStream(filePath);

pr.save(out, "");

}catch(IOException e) {//TODO Auto-generated catch block

e.printStackTrace();

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

br.close();

}catch(IOException e) {//TODO Auto-generated catch block

e.printStackTrace();

}

}

}

}

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值