如何在Spring Boot中从资源中读取JSON文件
2022-09-03 17:01:06
使用Spring Boot 2.1.5 Release,创建了以下示例Spring Boot微服务:
Maven 项目结构:
MicroService
│
pom.xml
src
│
└───main
│
├───java
│ │
│ └───com
│ └───microservice
│ │
│ └───MicroServiceApplication.java
│
└───resources
│
└───data.json
│
application.properties
拥有以下 JSON 文件(在 src/main/resources/data.json 中):
{"firstName": "John", "lastName": "Doe"}
微服务应用:
@SpringBootApplication
public class MicroServiceApplication {
@Bean
CommandLineRunner runner() {
return args -> {
String data = FilePathUtils.readFileToString("../src/main/resources/data.json", MicroServiceApplication.class);
System.out.println(data);
};
}
public static void main(String[] args) {
SpringApplication.run(MicroServiceApplication.class, args);
}
}
引发以下异常:
java.lang.IllegalStateException: Failed to execute CommandLineRunner
...
Caused by: java.io.IOException: Stream is null
FilePathUtils.java:
import io.micrometer.core.instrument.util.IOUtils;
import java.io.IOException;
import java.io.InputStream;
import java.nio.charset.Charset;
public class FilePathUtils {
public static String readFileToString(String path, Class aClazz) throws IOException {
try (InputStream stream = aClazz.getClassLoader().getResourceAsStream(path)) {
if (stream == null) {
throw new IOException("Stream is null");
}
return IOUtils.toString(stream, Charset.defaultCharset());
}
}
}
我可能做错了什么?