1.編寫一個公共類PropertiesUtil.class,方便以後讀取配置文件
public class PropertiesUtil {
private static Logger logger = LoggerFactory.getLogger(PropertiesUtil.class);
private static Properties props;
//tomcat啓動,讀取配置。使用靜態塊,執行且執行一次
static{
String fileName = "config/common.properties";
props = new Properties();
try {
props.load(new InputStreamReader(
PropertiesUtil.class.getClassLoader()
.getResourceAsStream(fileName),"UTF-8"));
} catch (IOException e) {
logger.error("配置文件讀取異常",e);
}
}
//通過properties配置文件中的key獲取value
public static String getProperty(String key) {
String value = props.getProperty(key.trim());
if(StringUtils.isBlank(value)){
return null;
}
return value.trim();
}
//重載,有默認值
public static String getProperty(String key,String defaultValue) {
String value = props.getProperty(key.trim());
if(StringUtils.isBlank(value)){
return defaultValue;
}
return value.trim();
}
}
2.properties.xml文件 key=value
ftp.server.http.prefix=http://img.common.com
3.使用
String str= PropertiesUtil.getProperty("ftp.server.http.prefix","http://img.common.com")