[英]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.我希望能够在 heroku 上在线部署我的 spring 引导应用程序。 My app loads data from a static.json file which is located on my resources folder.
我的应用程序从位于我的资源文件夹中的 static.json 文件加载数据。
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.
由于某种原因,我无法从 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;
}
Since data.json
is moved inside JAR which is deployed on heroku, try using getResourceAsStream(path)
instead getResource()
. 由于
data.json
是在部署在heroku上的JAR中移动的,因此请尝试使用getResourceAsStream(path)
而不是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.如果它是 spring 项目,则资源文件夹中的文件将被复制到 mvn build 上的
target/classes
文件夹。 So to use it, do following:因此,要使用它,请执行以下操作:
import org.springframework.util.ResourceUtils;
ResourceUtils.getFile("classpath:static/data/data.json")
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.