springboot项目读取resource目录下的 txt 文件 ,在本机可以,发布后读取不到。
报错的代码如下:
public static List<String> getRank() throws IOException {
ClassPathResource classPathResource = new ClassPathResource("key.txt");
List<String> list = Files.readLines(classPathResource.getFile(), Charset.forName("utf-8"));
List<String> list=Arrays.asList(strs);
return list;
}
解答:这是因为打包后Spring试图访问文件系统路径,但无法访问JAR中的路径。 因此必须使用resource.getInputStream()
修改为如下代码即可
public static void getRank() throws IOException { ClassPathResource classPathResource = new ClassPathResource(key.txt); byte[] keywordsData = FileCopyUtils.copyToByteArray(classPathResource.getInputStream()); String[] strs = new String(keywordsData, Charset.forName("utf-8")).split("|"); List<String> list=Arrays.asList(strs); return list; }