IOException When Trying to Load JSON data file via Spring Boot Command Line Runner

情到浓时终转凉″ 提交于 2020-01-30 09:17:24

问题


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?


回答1:


While @Deadpool has provided the answer, I would like to add that when the artifact of spring boot is created there is no such src/main/ folder anymore (you can open the spring boot artifact and make sure by yourself).

So you can't load resources like this:

FilePathUtils.readFileToString("../src/main/resources/data.json", MicroServiceApplication.class);

Spring indeed has an abstraction called Resource that can be used in the application, that can even be injected into the classes / configuration:

@Value("classpath:data/data.json")
Resource resourceFile;

Notice the prefix "classpath" it means that the resource will be resolved from the classpath (read everything properly packaged into the artifact).

There is a pretty good Tutorial that can be handy




回答2:


In spring boot project you can use ResourceUtils

Path file = ResourceUtils.getFile("data/data.json").toPath();

or ClassPathResource

String clsPath =  new ClassPathResource("data/data.json").getPath();


来源:https://stackoverflow.com/questions/58703834/ioexception-when-trying-to-load-json-data-file-via-spring-boot-command-line-runn

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!