Using Spring Boot 2.1.5 Release, have created the following sample Spring Boot Microservice:
Maven Project Structure:
MicroService
│
pom.xml
src
│
└───main
│
├───java
│ │
│ └───com
│ └───microservice
│ │
│ └───MicroServiceApplication.java
│
└───resources
│
└───data.json
│
application.properties
Have the following JSON file (inside src/main/resources/data.json):
{"firstName": "John", "lastName": "Doe"}
MicroServiceApplication:
@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);
}
}
Throws the following exception:
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());
}
}
}
What am I possibly being doing wrong?
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…