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