key.txt cannot be resolved to absolute file path because it does not reside in the file system

springboot项目读取resource目录下的 txt 文件 ,在本机可以,发布后读取不到。

报错的代码如下:

public static List getRank() throws IOException {

    ClassPathResource classPathResource = new ClassPathResource("key.txt");
    List list = Files.readLines(classPathResource.getFile(), Charset.forName("utf-8")); 
    List 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 list=Arrays.asList(strs);
    return list;
}

 

 

你可能感兴趣的:(java)