首页 > 解决方案 > 如何在 Spring Boot 上读取部署的静态文件

问题描述

我希望能够在 heroku 上在线部署我的 Spring Boot 应用程序。我的应用程序从位于我的资源文件夹中的静态 .json 文件加载数据。

在此处输入图像描述

到目前为止,我已经尝试过这段代码,但它不起作用。由于某种原因,我无法从 json 文件中读取数据。

    public List<Category> getAllCategories() throws FileNotFoundException
    {
       Gson gson = new Gson();
       ClassLoader classLoader = getClass().getClassLoader();
       File file = new File(classLoader.getResource("static/data/data.json").getFile());
       JsonReader reader = new JsonReader(new FileReader(file.getPath()));
       List<Category> allCategories = gson.fromJson(reader, new TypeToken<List<Category>>(){}.getType());

       return allCategories;
    }

标签: javaspring-bootherokudeployment

解决方案


由于data.json已移动到部署在 heroku 上的 JAR 中,因此请尝试getResourceAsStream(path)使用getResource(). 伪代码可能是,

Gson gson = new Gson();
ClassLoader classLoader = getClass().getClassLoader();
InputStream in = classLoader.getResourceAsStream("static/data/data.json");
JsonReader reader = new JsonReader(new InputStreamReader(in));
List<Category> allCategories = gson.fromJson(reader, new TypeToken<List<Category>>(){}.getType());

推荐阅读