1、第一种读取与jar包在同一个目录中的文件,也就是没打包到jar包里面

读取方式:
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import org.springframework.core.io.ClassPathResource;
String filePath = "./data.json";
ClassPathResource classPath = new ClassPathResource(filePath);
JSONObject jsonObject = JSON.parseObject(classPath.getInputStream(),JSONObject.class);
System.out.println(jsonObject);
2、第二种读取将文件打包到jar里面的情况

文件放在resurces里面
String filePath = "./data.json";
InputStream inputStream = getClass().getResourceAsStream(filePath);
JSONObject jsonObject = JSON.parseObject(inputStream,JSONObject.class);
System.out.println(jsonObject);
两种方式
本文介绍了两种在Java中读取JSON文件的方法:一种是读取与jar包在同一目录但未被打包进jar的文件;另一种是读取被打包进jar包内部资源文件夹中的文件。通过使用不同的输入流方式,可以实现对文件内容的有效解析。
640

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



