import java.io.FileOutputStream;
import java.io.InputStream;
import java.util.Properties;
import org.apache.log4j.Logger;
import org.apache.struts2.util.ClassLoaderUtils;
/**
* 读取properties 工具类
*
* @author Jarven
*
*/
public class PropertiesUtil {
private static final Logger log = Logger.getLogger(PropertiesUtil.class);
private static Properties prop = new Properties();// 属性集合对象
static {
try {
InputStream is = null;
is = ClassLoaderUtils.getResourceAsStream("config.properties", PropertiesUtil.class);
if (is != null) {
prop.load(is);// 将属性文件流装载到Properties对象中
is.close();// 关闭流
}
} catch (Exception e) {
log.error("读取配置文件出错:" + e);
}
}
/**
* 根据key获取配置的值
*
* @param key
* @return
*/
public static String getProperties(String key) {
if (key == null)
return null;
return prop.getProperty(key);
}
/**
* 根据key获取配置的值,若没有,则取传过来的默认的值
*
* @param key
* @param defaultValue
* @return
*/
public static String getProperties(String key, String defaultValue) {
if (key == null)
return null;
return prop.getProperty(key, defaultValue);
}
/**
* 写配置文件
*
* @param key
* @param value
* @return
*/
public static boolean setProperty(String key, String value) {
boolean flag = false;
try {
prop.setProperty(key, value);
flag = true;
} catch (Exception e) {
log.error("写配置文件出错:" + e);
flag = false;
}
return flag;
}
public static void main(String[] args) {
try {
// 获取属性值,sitename已在文件中定义
System.out.println("获取属性值:cas.sso.webserviceurl="
+ prop.getProperty("cas.sso.webserviceurl"));
// 获取属性值,country未在文件中定义,将在此程序中返回一个默认值,但并不修改属性文件
// System.out.println("获取属性值:country=" + prop.getProperty("country",
// "中国"));
// 修改sitename的属性值
prop.setProperty("sitename", "Boxcode");
// 添加一个新的属性studio
prop.setProperty("studio", "Boxcode Studio");
// 文件输出流
FileOutputStream fos = new FileOutputStream("prop.properties");
// 将Properties集合保存到流中
prop.store(fos, "Copyright (c) Boxcode Studio");
fos.close();// 关闭流
} catch (Exception e) {
e.printStackTrace();
}
}
}