首先springboot项目使用内置tomcat打成jar包后如果将文件放在resource下 需要使用 如下方式读取
因为打成jar包后资源文件是在jar包里的,通过File获取资源绝对路径是不能访问到jar包里面的,因此使用ResourceLoader去获取文件。
public List<CountryInfo> countryInfo() {
ArrayList<CountryInfo> list = new ArrayList<>();
try {
ResourceLoader resourceLoader = new DefaultResourceLoader();
Resource resource=resourceLoader.getResource("classpath:listOfCountryNames.txt");
InputStream is = resource.getInputStream();
IOUtils.readLines(is).forEach(line->{
String str = (String) line;
String[] splits = str.split("=");
CountryInfo info=new CountryInfo(splits[1],splits[0]);
list.add(info);
});
}catch (IOException e){
log.error("文件读取异常",e);
}
return list;
}