自己写了一个读取properties的程序,废话不说了,直接上代码:(附件中有eclipse的工程源码)
package my.config;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Properties;
import my.util.ResourceUtil;
import my.util.StringUtil;
/**
* 读取xxx.properties文件
* @author zs
*
*/
public class Config {
private final static String CONFIG_NAME = "config.properties";
private static Properties pro = null;
/**
* 获取文件的Properties
* @param fileName
*/
public static Properties getConfigInfo(){
try{
InputStream in = ResourceUtil.getResourceStream(StringUtil.nvl(CONFIG_NAME));
pro = new Properties();
pro.load(in);
in.close();//注意要关闭
return pro;
}catch(Exception e){
e.printStackTrace();
System.out.println("获取 Porperties失败");
return null;
}
}
/**
* 根据key值,读取value
* @param key
* @return
*/
public static String readConfig(String key){
try{
if(pro==null){
pro = getConfigInfo();
}
String value = StringUtil.nvl(pro.getProperty(key));
System.out.println("读取成功!");
if(("").equals(value)){
System.out.println("没有找到"+key+"对应的值");
}
return value;
}catch(Exception e){
e.printStackTrace();
System.out.println("读取失败!");
return "";
}
}
/**
* 根据key 和value 值 ,写入配置文件中,如果key存在,就做修改,如果不存在,就做增加
* @param key
* @param value
*/
public static void writeConfig(String key , String value){
try{
if(pro==null){
pro = getConfigInfo();
}
String realPath = ResourceUtil.getResourceRealPath(StringUtil.nvl(CONFIG_NAME));
OutputStream fos = new FileOutputStream(realPath);
pro.setProperty(key, value);
pro.store(fos, "Update '" + key + "' value");
fos.close();
getConfigInfo();
System.out.println("写入成功!");
System.out.println("写入的内容为:"+key+"="+value);
}catch(Exception e){
System.out.println("写入失败!");
e.printStackTrace();
}
}
}
分享到:
2011-10-14 14:13
浏览 1212
评论