之前一直没有注意,当去加载resources下的配置文件时,忘记怎么做了,这次整理了一下这篇文章
一、加载配置文件方法
config.properties
appId=*******
apiKey=*******
PropertiesConfig
public class PropertiesConfig {
private static final String APP_ID;
private static final String API_KEY;
static {
Properties properties = new Properties();
try {
ClassPathResource resource = new ClassPathResource("config.properties");
InputStream in = resource.getInputStream();
BufferedReader bf = new BufferedReader(new InputStreamReader(in,"UTF-8"));
properties.load(bf);
} catch (IOException e) {
throw new RuntimeException("加载配置文件失败");
}
APP_ID = properties.getProperty("appId");
API_SECRET = properties.getProperty("apiSecret");
}
public static String getAppId() {
return APP_ID;
}
public static String getApiKey() {
return API_KEY;
}
二、加载resources中的txt到map
public static Map<String,String> readTxtFile() {
Map<String,String> map = new HashMap<>();
try {
final String[] txtFiles = new String[]{
"xxxx.txt","xxxx.txt"};
for (String fileName : txtFiles) {
byte[] bytes;
ClassPathResource classPathResource = new ClassPathResource(fileName);
//获取文件流
InputStream keyStream = classPathResource.getInputStream();
bytes = IOUtils.toByteArray(keyStream);
keyStream.read(bytes);
keyStream.close();
ByteArrayInputStream certBis = new ByteArrayInputStream(bytes);
InputStreamReader input = new InputStreamReader(certBis);
BufferedReader bf = new BufferedReader(input);
String line;
while((line=bf.readLine()) != null){
//取到第一行的字符 line ,根据业务需要随意处理,这里是处理 :分隔 存了下map
String[] ms = line.split(":");
map.put(ms[0],ms[1]);
}
}
log.info("------加载Q&A预设文件: " + map);
return map;
} catch (IOException e) {
log.error("加载Q&A预设文件失败",e);
}
return map;
}