如何在Spring Boot部署时读取静态文件

时间:2018-09-23 12:33:32

标签: java spring-boot heroku deployment

我希望能够在heroku上部署我的spring boot应用程序onlne。我的应用程序从资源文件夹中的静态.json文件加载数据。

enter image description here

到目前为止,我已经尝试过此代码,但是它不起作用。由于某种原因,我无法从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;
    }

2 个答案:

答案 0 :(得分:1)

由于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());

答案 1 :(得分:0)

您是否可以将数据文件夹直接移到资源下,因为此处的静态资源路径可能会冲突,因此可以在下面使用。

File file = new File(classLoader.getResource("data/data.json").getFile());