【发布时间】:2019-07-27 23:58:21
【问题描述】:
我有一个 spring-boot 应用程序,我有一些文件放在 /src/main/java/resources 中,我试图在我的代码中读取它。当相同的代码尝试从 docker 容器中读取时,它说文件不存在。相同的代码通过 localhost 可以正常工作
文件位于 /src/main/java/resources/data 文件夹下,这是我尝试读取文件的代码
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();
}
文件路径示例:src/main/resources/data/get-products/1420-17612-82.json Docker 文件内容
{
"commands":
[
"rm -rf .tmp",
"git clone git@github.com:{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"
]
}
【问题讨论】:
-
如何编译和运行应用程序?容器是否甚至可以访问
src?即使没有 Docker,Java 应用程序通常也会被编译成 jar 文件,在部署后不会显示其源代码,您必须从类加载器加载资源,而不是从文件系统加载。 -
好的。在 /classes/data 下编译后它们位于我的类路径中,我正在尝试通过类加载器加载它们
-
所以我编辑了我的问题并附上了完整的源代码
-
对不起 /src/main/resources 是正确的路径。另外,在问题中添加 dockerfile 内容。
-
是的,它是 /src/main/java/resources
标签: java spring-boot docker docker-compose