我有一个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"
]
}
src
目录?即使没有 Docker,通常情况下,Java 应用程序也会被编译成 jar 文件,在部署后就不再具有其源代码,并且需要从 classloader 而不是文件系统加载资源。 - Thilo