SpringBoot 读取本地资源文件方式总结

第一步:读取资源文件位置的三种方式:

1、字符串形式:
String path = ResourceUtils.getURL("classpath:data.json").getPath();

2、流形式
InputStream inputStream  = getClass().getClassLoader().getResourceAsStream("data.json");

3、资源方式
Resource resource = new ClassPathResource("data.json");

在springBoot resource 资源文件下存在data.json 资源文件。

应用场景: SringBoot 读取本地资源文件,完成数据相关初始化

package com.zzg.controller;

import java.io.File;
import java.util.List;
import java.util.regex.Pattern;
import java.util.stream.Collectors;

import org.apache.commons.io.FileUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Controller;
import org.springframework.util.ResourceUtils;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;

@Controller
@RequestMapping("/api/location")
@CrossOrigin
@Api(value = "模拟测试Controlle", tags = "模拟测试操作服务")
public class TestLocation {
	static JSONArray array = null;
	static {
		try {
			String path = ResourceUtils.getURL("classpath:data.json").getPath();
			File file = new File(path);
			if(file.exists()) {
				String content = FileUtils.readFileToString(file,"UTF-8");
				if(StringUtils.isNotEmpty(content)) {
					array = JSONArray.parseArray(content);
				}
			}
		} catch (Exception e) {
			// TODO Auto-generated catch block
			System.out.println(e.getMessage());
		}
	}
	
	@RequestMapping(value="/find", method={RequestMethod.GET}, produces = "application/json;charset=UTF-8")
	@ResponseBody
	@ApiOperation(httpMethod = "GET", value = "模拟测试对象查询")
	public String find() {
		List<JSONObject> list = null;
		if(array != null) {
			list = array.stream().filter(item ->{
				JSONObject object = (JSONObject)item;
				String code = object.getString("code");
				return Pattern.matches("^[\\s\\S]*0000$", code);
			}).map(item ->{
				return (JSONObject)item;
			}).collect(Collectors.toList());
		}
		
		JSONObject obj = new JSONObject();
		obj.put("code", 0);
		obj.put("data", list);
		return obj.toJSONString();
	}

}


版权声明:本文为zhouzhiwengang原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。