我有一个 spring-boot 应用程序,并且在/src/main/java/resources 中放置了一些文件,我试图在代码中读取它。当相同的代码尝试从 docker 容器读取时,它会说文件不存在。相同的代码通过本地主机运行得很好
这些文件位于/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"
]
}
最佳答案
所以......你搞乱了文件
的路径和类路径中的资源。 File f = new File(filePath);
的原因是什么?
事情是这样的:
如果您使用
File
- 文件必须可供 JVM 使用,并且只要您使用相对路径(如data\folderxxx\filexxx.json
),它就必须在容器文件系统中可用。 IE。data
文件夹必须放置在镜像中或从外部准确安装到 JVM 运行的目录如果您使用
ClassLoader
和ResourceAsStream
,则data
目录的根目录必须在 JVM 的类路径中定义或位于 Jar 中文件 - 它也是类路径中的根。检查您的 jar 文件 - 如果data
目录位于 jar 的根目录中 - 一切正常,文件将可以通过this.getClass().getClassLoader().getResourceAsStream(filePath)
获得,但不适用于new File(filePath)
!
如果没有 - 让它发生或相应地更新 ResourceAsStream
的文件路径。
关于java - 无法通过docker容器读取文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55021077/