3

I am working on a gradle based service that should run in a docker container in a kubernetes cluster. Locally, I can access the resources, some json files used for CouchDb initialisation. Once I build and deploy the service in Docker, the files are no longer accessible and I get file not found exception and can't start the service. I can see that my folder is in the generated jar but I can't access the files. I am using it like follows:

DesignDocument design = DesignDocumentManager.fromFile("design-documents/documents.json");

which comes from the IBM Cloudant Java Client API. I have tried different versions from the path, i.e. with a leading slash or the absolute path from the project.

taz_
  • 137
  • 3
  • 13

2 Answers2

3

The API does not have an alternative to File, which is an operating system File. So use a temporary file.

InputStream in = getClass().getResourceAsStream(
        "/design-documents/documents.json");
Path tempPath = Files.createTempFile("desdoc-", ".json");
Files.copy(in, tempPath);
DesignDocument design = DesignDocumentManager.fromFile(tempPath.toFile());
Files.delete(tempPath);

Note the leading / for Class.getResource(AsStream).

Joop Eggen
  • 107,315
  • 7
  • 83
  • 138
  • 1
    that, worked for me, but we decided on another option, namely to copy the resource files into the container using COPY in the Dockerfile. – taz_ May 24 '18 at 14:11
  • Hi, Can you share how you accessed the files in the COPY command? Looking to do something similar. – Aishwarya Soni Dec 06 '22 at 07:52
0

As @taz_ said, another way is to COPY the file from the resource in the Dockerfile

COPY src/main/resources/design-documents/documents.json /root/design-documents/documents.json

and then get it directly from there

DesignDocument design = DesignDocumentManager.fromFile("root/design-documents/documents.json");

In my case, I needed it as a String so this is what I did

public String readJsonAsString(String filePath) throws Exception {
    return new String(Files.readAllBytes(Paths.get(filePath)));
}

The filePath was this

private static final String DOCUMENTS_JSON = "/root/design-documents/documents.json";
datruq
  • 31
  • 1
  • 3