java - 如何在 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;
}
解决方案
由于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());
推荐阅读
- javascript - MediaRecorder 类在 Electron APP 中不可用
- react-native - 深度链接 - 如果应用程序关闭则不起作用
- c# - 我需要使用 regex (Address) C# 替换一些单词
- java - 如何读取 SOAP 请求正文元素而不在 Java SpringWS 中的 xsd 或 wsdl 中声明它?
- opencv - 如何在 google colab 中使用 opencv 显示 mp4
- go - Kafka:Sarama、幂等性和 transactional.id
- r - 我可以在 ggplot 条形图中选择要着色的特定行吗?
- google-analytics - Google Analytics(分析)目标转化限制
- python - 大小为 200 和 300 的两个数组。如何连接数组以使其成为 200x300?
- groovy - 字符串中的对象名称 - 如何使用它