文件目录:
目标
在ReadJsonSample中获取lisi.json 文件中的内容
错误原因
一开始我是用
File file = new File(ReadJsonSample.class.getResource("/lisi.json").getFile());
但是IDEA总是报错
Exception in thread "main" java.lang.NullPointerException
at com.xxxx.demo.json.ReadJsonSample.main(ReadJsonSample.java:32)
原因是我在代码中使用了ReadJsonSample.class.getResource
方法,而ReadJsonSample.class
这个类是在运行时动态加载的,这个class文件保存在另外的文件夹中,
而这个文件夹中是没有我需要的lisi.json
文件的,因此找不到该文件。
解决方法
先获取项目在计算机中的绝对路径A,然后在A的基础上指定json文件
File directory = new File("");
File file = new File(directory.getCanonicalPath()+
"/src/main/java/com/xxxx/demo/json/lisi.json");