springboot工程中读取json文件是一个非常常见的操作,在本地idea运行调试的时候读取json文件没有任何问题,但是打包发布后运行会报读取不到json文件的问题,解决方法如下
- 要将json文件放到static目录下,如/static/config/
- 读取json文件要用ClassPathResource和fastJson操作
示例:
// 1
ClassPathResource resource = new ClassPathResource("static/config/Info.json");
// 2
JSONObject jsonObject = JSONObject.parseObject(FileUtil.readJson(resource ));
// 3
public static String readJson(ClassPathResource classPathResource) {
String jsonStr = "";
try {
InputStream inputStream = classPathResource.getInputStream();
Reader reader = new InputStreamReader(inputStream, "utf-8");
int ch = 0;
StringBuffer sb = new StringBuffer();
while ((ch = reader.read()) != -1) {
sb.append((char) ch);
}
reader.close();
jsonStr = sb.toString();
return jsonStr;
} catch (IOException e) {
e.printStackTrace();
return null;
}
}
// 4
jsonObject .get("");
这样即可在打包运行时正确读取json文件,并转成json对象进行后续操作。
当SpringBoot应用在本地运行时能正常读取JSON文件,但在打包发布后出现无法读取的问题。解决方法是将JSON文件放入静态资源目录`static`下,通过`ClassPathResource`和`fastJson`进行读取。示例代码中展示了如何从`/static/config/Info.json`读取并转换为JSONObject,确保了打包运行时的正确读取。

被折叠的 条评论
为什么被折叠?



