springboot中,如何从资源文件加载文件

springboot中,如何从资源文件加载文件

写在前面

核心还是IO操作,主要包括以下两个

  • ResourceUtils
  • ClassPathResource

一、ResourceUtils

public JsonInformationHereAsReturnType getJsonContent() {

    File file = ResourceUtils.getFile("classpath:sample.json");
            //Read File Content
            String content = new String(Files.readAllBytes(file.toPath()));

    return content;
}

二、ClassPathResource

 @Before
    public void t1() {
        try {
            // 根据resource文件路径,生成文件
            ClassPathResource resource = new ClassPathResource("db/list.json");
            // 解析文件为指定编码的字符串
            String string = CharStreams.toString(new InputStreamReader(resource.getInputStream(), "UTF-8"));
            list = JSONArray.parseArray(string, Department.class);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

需要注意

在本地环境下,ResourceUtils 可以正常读取到我需要的文件,但是有时候,再 部署到 Linux 上时,会有
问题,ResourceUtils.getFile()不能嵌套在jar文件中,如果需要在 SpringBoot 项目中读取资源文件,最好使用 ClassPathResource.getInputStream()。

发布了187 篇原创文章 · 获赞 28 · 访问量 6万+

猜你喜欢

转载自blog.csdn.net/qq_42105629/article/details/103837153