简体   繁体   中英

How to read file from folder in Java Micronaut

On a Micronaut project I have a folder structure like the following:

myproject
     |____mocks
     |      |_____file.json
     |
     |____src
           |_____main
                   |_____java
                           |_____s.p.d.b.controllers
                                     |________MyController.java

I want to read the content of file.json and return it as the response of a GET request handler on MyController.

@Controller("${endpoints.all.path}/v1/file")
public class MyController {
    private static final Logger LOG = LoggerFactory.getLogger(MyController.class);

    @Get
    public HttpResponse<List<FileModel>> getAll() {
        ObjectMapper mapper = new ObjectMapper();
        String file = "mocks/file.json";
        String jsonString;
        List<FileModel> fileList;
        try {
            jsonString = new String(Files.readAllBytes(Paths.get(file)));
            fileList = mapper.readValue(jsonString, new TypeReference<List<FileModel>>(){});
        } catch (IOException e) {
            LOG.error(e.getMessage());
            return HttpResponse.serverError();
        }
        return HttpResponse.ok(fileList);
    }
}

This works locally when running from IntelliJ. It doesn't work once I deploy the application to my K8S cluster. On the deployed app I'm getting an error: [default-nioEventLoopGroup-1-2] ERROR c.spdbc.MyController

For some reason the files can't be parsed or are not available to the deployed app. Is there something I need to do to load them or add them to the classpath?

The location of the files was inadequate. I moved them to the resources folder and then I could access them easily.

myproject
     
     |
     |____src
           |_____main
           |       |_____java
           |               |_____s.p.d.b.controllers
           |                         |________MyController.java
           |
           |
           |_____resources
                     |
                     |_______mocks

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM