简体   繁体   中英

How to read a static file on deployment on Spring Boot

I want to be able to deploy my spring boot application onlne on heroku. My app loads data from a static.json file which is located on my resources folder.

在此处输入图像描述

So far I've tried this code but it doesn't work. For some reason I can't read the data from the json file.

    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;
    }

Since data.json is moved inside JAR which is deployed on heroku, try using getResourceAsStream(path) instead getResource() . pseudocode could be,

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

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

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

If it's a spring project, files present in resources folder gets copied to target/classes folder on mvn build. So to use it, do following:

import org.springframework.util.ResourceUtils;

ResourceUtils.getFile("classpath:static/data/data.json")

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM