配置文件工具类
public class PropertiesHelper {
private static final Logger logger = LoggerFactory.getLogger(PropertiesHelper.class);
private Properties props;
public PropertiesHelper(String fileName) {
readPropertiesFile(fileName);
}
private void readPropertiesFile(String clazzPathFile) {
props = new Properties();
InputStreamReader is = null;
try {
is = new InputStreamReader(PropertiesHelper.class.getClassLoader().getResourceAsStream(clazzPathFile), "UTF-8");
props.load(is);
} catch (Exception e) {
logger.error("Load properties file" + clazzPathFile + ", exception" + e.getMessage());
new RuntimeException("Load properties file" + clazzPathFile, e);
} finally {
if (is != null)
try {
is.close();
} catch (IOException e) {
logger.info("Close file exception, " + e.getMessage());
}
}
}
/**
* 根据key读取对应的value
*
* @param key
* @return
*/
public String get(String key) {
return props.getProperty(key);
}
/**
* 得到所有的配置信息
*
* @return
*/
public Map<?, ?> getAll() {
Map<String, String> map = new HashMap<String, String>();
Enumeration<?> enu = props.propertyNames();
while (enu.hasMoreElements()) {
String key = (String) enu.nextElement();
String value = props.getProperty(key);
map.put(key, value);
}
return map;
}
}
使用
private List<String> getAll() {
PropertiesHelper propertiesHelper = new PropertiesHelper("config/buss.properties");
String rs = propertiesHelper.get("ip.list");
if (StringUtils.isNotBlank(rs)) {
return Arrays.asList(rs.split(","));
}
return null;
}
属性文件
ip.list=120.0.0.1,127.0.0.2