springboot读取resource下json文件出现空指针异常

1.pom包依赖

                
			com.alibaba
			fastjson
			1.2.30
		
		
			commons-io
			commons-io
			2.4
		

2.读取配置json文件

String path = getClass().getClassLoader().getResource("flt/test.json").getPath();
		path = path.replace("\\", "/");
		System.out.println(path);
		String input = null;
		JSONArray jsonArray = null;
		try {
			input = FileUtils.readFileToString(new File(path), "UTF-8");
			JSONObject jsonObject = JSONObject.parseObject(input);
			if (jsonObject != null) {
				jsonArray = jsonObject.getJSONArray("habby");
				System.out.println(jsonArray);
			}
		} catch (Exception e) {

		}
		System.out.println("kaishi:"+input);

读取json文件到此结束。

3.出现报空指针异常:这里主要有两种情况

(1):打成jar包后,读取的配置json文件为jar包里面的(这里只能使用流的形式去读取)

1.    InputStream inputStream = Thread.currentThread().getContextClassLoader().getResourceAsStream("flt/test.json");

input = IOUtils.toString(inputStream , "UTF-8");
			JSONObject jsonObject = JSONObject.parseObject(input);


2. 
 ClassPathResource resources = new ClassPathResource(path);

			resources.getInputStream();

其他方法也皆为流的形式,推荐使用上面的1方法。

(2): 打成jar包后,读取的配置json文件为jar包外面的。自定义的文件夹。主要难点:获取jar包所在文件路径

a. 此时主要错误为文件路径有错: demo版使用此方法  如下:

        System.out.println(System.getProperty("user.dir"));

 使用获取系统变量的方法,获取当前运行jar包所在的路径: 例如 E:\webpack , 后面拼自己自定义的文件路径

b.获取jar包所在路径,正式版(需要会正确的打包)

  ApplicationHome h = new ApplicationHome(getClass());
        File jarF = h.getSource();
        System.out.println(jarF.getParentFile().toString());

分析原因:a.主要是因为springboot内置Tomcat。打包文件后。通过文件读取文件路径获取数据的方式行不通,因为无法直接读取压缩包中的文件,读取只能通过流的方式读取。这里还与类的加载器有关,常用的为appClassLoader,但打成jar包后,使用的是LoadClassLoader(在另一博客中看到。链接后续补上), 使用getContextClassLoader()方法使得加载类采用的是同父类加载器一致的加载器。则不会因类加载器不同导致报错。

参考链接:https://blog.csdn.net/liangcha007/article/details/88526181

实践了此次demo后,发现要学会如何使用maven打包。如使用 assembly打包。

如需要demo可以留言。


 

你可能感兴趣的:(springboot,json)