Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Cannot read file via docker container

I have a spring-boot application and I have some files placed inside /src/main/java/resources which I am trying to read it in my code. When the same code tries to read from docker container it says file does not exist. The same code works perfectly fine via localhost

The files are under /src/main/java/resources/data folder and this is my code which tries to read the file

 private String getJson(String folderName, String id, StringBuilder sb) throws Exception {
        String responseJson = null;
        String filePath = "data" + File.separator + folderName + File.separator + id + ".json";
        LOG.info("printing filePath : " + filePath);
        LOG.info("printing id : " + id);
        File f = new File(filePath);
       // if(f.exists()){
            try (InputStream inputStream = this.getClass().getClassLoader().getResourceAsStream(filePath)) {
                LOG.info("printing inputStream : " + inputStream);
                if (inputStream != null) {
                    responseJson = IOUtils.toString(inputStream, StandardCharsets.UTF_8.name());
                }
                if (responseJson == null || responseJson.isEmpty()) {
                    LOG.info("json response is null : ");
                    throw new JsonNotFoundException(Constant.JSON_NOT_FOUND);
                }
                sb.append(responseJson);
            } catch (IOException e) {
                LOG.info("IO exception : ");
                throw new IOException(e);
            } catch (Exception e) {
                LOG.info(" exception : ");
                throw new Exception(e);
            }
//        }
//        else{
//            LOG.info("file doesnt exists : " + filePath);
//        }
        return sb.toString();
    }

An example for the file path : src/main/resources/data/get-products/1420-17612-82.json Docker file content

{
  "commands":
  [
    "rm -rf .tmp",
    "git clone [email protected]:{orgnname}/{test-service.git} -b COECP-973-Configure-logging-mechanism-for-Service .tmp/test-service",
    "docker build .tmp/test-service/.docker/build/db -t local/test-service/db",
    "docker build .tmp/test-service -t local/test-service/app"
  ]
}
like image 653
Vinaya Nayak Avatar asked Sep 05 '25 03:09

Vinaya Nayak


1 Answers

I have had faced the same issue earlier, though our requirement got more complex over time, but the following code should solve your problem:

    ClassPathResource cp = new ClassPathResource("relative_path_to_file");
    File f = null;

    if (cp.exists())
        f = cp.getFile();
like image 113
Shariq Avatar answered Sep 08 '25 01:09

Shariq