springBoot中同时获取key及value值存入map中,配置文件(文件在resource下)如下:
config.suyl=19931216
config.candy=19940912
config.child=20210505
加载配置工具类:
package com.suyl.candy.tools;
import cn.hutool.core.io.FileUtil;
import org.apache.poi.util.IOUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URISyntaxException;
import java.util.Iterator;
import java.util.Map.Entry;
import java.util.Properties;
/**
* @author candy
* @version 1.0
* @createDate 2020/5/16 22:58
* @description 获取文件配置信息
*/
public class PropertiesUtils {
protected Logger logger = LoggerFactory.getLogger(getClass());
public Properties properties;
private String[] resourcesPaths;
// 无参构造
public PropertiesUtils() {
}
// 传入配置文件名称,可以多个
public PropertiesUtils(String... resourcesPaths) {
load(resourcesPaths);
}
// 加载配置文件信息
private void load(String[] resourcesPaths) {
this.resourcesPaths = resourcesPaths;
properties = new Properties();
for (String location : resourcesPaths) {
InputStream is = null;
try {
is = new FileInputStream(getAbsolutePath(location));
properties.load(is);
} catch (IOException ex) {
logger.info("Could not load properties from path:" + location + ", " + ex.getMessage());
} catch (Exception ex) {
logger.info("Could not load properties from path:" + location + ", " + ex.getMessage());
} finally {
IOUtils.closeQuietly(is);
}
}
}
// 获取根据key获取value
public Object getValue(String key) {
if (properties.containsKey(key)) {
return properties.getProperty(key);
}
return "";
}
// 获取文件绝对路径
public String getAbsolutePath(String filename) throws URISyntaxException {
if (!FileUtil.isAbsolutePath(filename)) {
filename = PropertiesUtils.class.getClassLoader().getResource(filename).toURI().getPath();
}
return filename;
}
public static void main(String[] args) {
long startTime = System.currentTimeMillis();
PropertiesUtils properties = new PropertiesUtils("application-map.properties", "application-map1.properties");
Iterator<Entry<Object, Object>> map = properties.properties.entrySet().iterator();
while (map.hasNext()) {
Entry<Object, Object> entry = map.next(); // 遍历获取key value
Object key = entry.getKey();
Object value = entry.getValue();
System.out.println(key + "=" + value);
}
System.out.println("load time :" + (System.currentTimeMillis() - startTime) + "ms");
}
}
如果配置文件key或value含有中文,可以把中文转为ASCII代码中获取到的就是中文(否则会乱码,ASCII与中文互转网站点此),如下:
config.suyl=19931216
config.candy=19940912
config.child=20210505
# 百度=https://www.baidu.com/
\u767e\u5ea6=https://www.baidu.com/
# 网易=https://www.163.com/
\u7f51\u6613=https://www.163.com/