最新开发出现一种情况,springboot打成jar包后读取不到文件,原因是打包之后,文件的虚拟路径是无效的,只能通过流去读取。
文件在resources下
public void test() {
List<String> names = new ArrayList<>();
InputStreamReader read = null;
try {
ClassPathResource resource = new ClassPathResource("name.txt");
InputStream inputStream = resource.getInputStream();
read = new InputStreamReader(inputStream, "utf-8");
BufferedReader bufferedReader = new BufferedReader(read);
String txt = null;
while ((txt = bufferedReader.readLine()) != null) {
if (StringUtils.isNotBlank(txt)) {
names.add(txt);
}
}
} catch (Exception e) {
e.printStackTrace();
} finally {
if (read != null) {
try {
read.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}