import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URL;
import java.util.Properties;
/**
* 属性文件读写工具
* @author shanl
*
*/
public class ResourceUtil {
private File configFile = null;
private Properties prop = null;
public ResourceUtil(URL url){
load(url);
}
/**
* 从classpath下查找指定资源<br/>
* 以类的部署目录为根,
* 例:conf/config.properties
* @param res
* @return
*/
public static ResourceUtil getInstanceByClasspath(String res){
URL url = ClassLoader.getSystemResource(res);
return new ResourceUtil(url);
}
/**
* 从classload下查找指定资源<br/>
* 以类的部署目录为根,
* 例:conf/config.properties
* @param res
* @return
*/
public static ResourceUtil getInstanceByClassloader(String res){
URL url = ResourceUtil.class.getClassLoader().getResource(res);
return new ResourceUtil(url);
}
/**
* 从配置文件中加载
* @param url
*/
private void load(URL url){
InputStream in = null;
try{
prop = new Properties();
configFile = new File(url.toURI());
in = new FileInputStream(configFile);
prop.load(in);
}catch(Exception ex){
throw new RuntimeException(ex);
}finally{
try{
if(null!=in) in.close();
}catch(Exception ex){
}
}
}
/**
* 返回某一项属性值
* @param key
* @return 返回属性值,如果不存在或没有值则返回""
*/
public String getProperty(String key){
return prop.getProperty(key,"");
}
/**
* 设置一项属性值
* @param key
* @param value
*/
public void setProperty(String key, String value){
prop.setProperty(key, value);
}
/**
* 移除一项
* @param key
*/
public void removeProperty(String key){
prop.remove(key);
}
/**
* 将当前各属性值保存至文件
*/
public void store(){
OutputStream out = null;
try{
out = new FileOutputStream(configFile);
prop.store(out, null);
}catch(Exception ex){
throw new RuntimeException(ex);
}finally{
try{
if(null!=out) out.close();
}catch(Exception ex){
}
}
}
}