最近在看 java8 的新特新,准备在实战项目中也运用进去。
所以今天来讨论一下在SpringBoot项目中,使用Stream来读取文件内容是否更优雅?
源码:
使用Stream的方式在SprinBoot项目中读area.json
文件,这个文件保存的是中国的省市区 json 数据
package com.itplh.demo.mock;
import org.apache.commons.io.IOUtils;
import org.springframework.util.ClassUtils;
import org.springframework.util.ResourceUtils;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
/**
* @author: tanpeng
* @date: 2019-06-19 16:22
* @desc:
*/
public class ReadJsonFile {
public static void main(String[] args) {
readJsonv1("classpath:com/itplh/demo/mock/json/area.json");
readJsonv2("classpath:com/itplh/demo/mock/json/area.json");
}
/**
* Stream的方式
* @param jsonSrc
* @return
*/
private static String readJsonv2(String jsonSrc) {
StringBuilder json = new StringBuilder("");
try {
File file = ResourceUtils.getFile(jsonSrc);
Path path = Paths.get(file.getPath());
Files.lines(path)
// 使用Stream很容易的过滤掉包含的空格
.map(String::trim)
.forEach(json::append);
System.out.println(json.toString());
System.out.println(json.toString().length());
} catch (IOException e) {
e.printStackTrace();
}
return json.toString();
}
/**
* 普通I/O流的方式
* @param jsonSrc
* @return
*/
private static String readJsonv1(String jsonSrc) {
String json = "";
try {
//换个写法,解决springboot读取jar包中文件的问题
InputStream stream = ClassUtils.getDefaultClassLoader().getResourceAsStream(jsonSrc.replace("classpath:", ""));
json = IOUtils.toString(stream);
System.out.println(json);
System.out.println(json.length());
} catch (IOException e) {
e.printStackTrace();
}
return json;
}
}
输出结果: 省略部分输出,实在太长了
[
...,
{
"value": "820000",
"label": "澳门特别行政区",
"children": [
{
"value": "820000",
"label": "澳门特别行政区",
"children": [
{
"value": "820000",
"label": "澳门特别行政区"
}
]
}
]
}
]
285420
[{"value": "110000","label": "北京市", ... ]
118330
总结:
- 使用Stream让编程变得更优雅,当然这两个方法对比效果可能不明显,因为方法一我没用传统的读取文件的方式,调用了别人的API
readJsonv2
方法中很容易的将两端的空格去掉,大大的缩小了http
响应数据包的体积,对我们服务端开发人员来说,这是我们更愿意看到的
注意:
readJsonv2()
虽然优雅,但是不能用于 SpringBoot 项目中读取jar
内的资源文件,否则会读取资源文件失败,引发线上事故
具体原因请参考:【Exception】java.io.FileNotFoundException SpringBoot项目打jar包运行,读取资源文件失败