SpringBoot 读取本地资源文件方式总结
java哥
阅读:1469
2021-03-31 13:44:59
评论:0
第一步:读取资源文件位置的三种方式:
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();
}
}
声明
1.本站遵循行业规范,任何转载的稿件都会明确标注作者和来源;2.本站的原创文章,请转载时务必注明文章作者和来源,不尊重原创的行为我们将追究责任;3.作者投稿可能会经我们编辑修改或补充。