spring boot项目运行jar包读取包内resources目录下的文件
摘要
Spring Boot 项目打包成 jar 包后,resources 目录下的文件将会被打包到 jar 包中。如果需要在 Spring Boot 项目运行 jar 包后读取 resources 目录下的文件,可以使用 this.getClass().getResourceAsStream() 方法。
结果输出:
bash
jar包程序读取包内resources下的文件:
{"name":"小明","age":45}
{"level":2,"name":"小丽","age":33}
码代码
文件所在目录/src/main/resources/static/my-json-data.json
java
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.apache.commons.io.IOUtils;
import org.springframework.stereotype.Component;
import javax.annotation.PostConstruct;
import java.io.IOException;
import java.io.InputStream;
@Component
public class MockRunApp {
static String jsonData1;
static String jsonData2;
/**
* Bean的构建后置过程中读取resources目录下的文件
*/
@PostConstruct
public void constructFunc(){
try {
InputStream resourceAsStream = this.getClass().getResourceAsStream("/static/my-json-data.json");
assert resourceAsStream != null;
String content = IOUtils.toString(resourceAsStream, "UTF-8");
ObjectMapper objectMapper = new ObjectMapper();
Object object = objectMapper.readValue(content, Object.class);
JSONArray objects = JSON.parseArray(JSONObject.toJSONString(object));
jsonData1 = objects.getString(0);
jsonData2 = objects.getString(1);
System.out.println("jar包程序读取包内resources下的文件:");
System.out.println(jsonData1);
System.out.println(jsonData2);
} catch (IOException e) {
throw new RuntimeException(e);
}
}
}