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();
}
}
}
}
}