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();
	}

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值