无法通过Docker容器读取文件

时间:2019-03-06 10:40:37

标签: java spring-boot docker docker-compose

我有一个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"
  ]
}

2 个答案:

答案 0 :(得分:1)

所以...您弄乱了File的路径以及类路径中的资源。拥有File f = new File(filePath);的原因是什么?

这是东西:

  1. 如果您使用File-文件必须对JVM可用,并且只要您使用data\folderxxx\filexxx.json之类的相对路径,它就必须在容器文件系统中可用。即data文件夹必须放置在映像中或从外部完全安装到JVM运行所在的目录中

  2. 如果您使用ClassLoader目录的ResourceAsStreamdata的根,则必须在JVM的类路径中定义或在Jar文件中-它是classpath中的根,例如好。检查您的jar文件-如果data目录位于jar的根目录中-一切正常,文件将由this.getClass().getClassLoader().getResourceAsStream(filePath)提供,而new File(filePath)则不可用!

如果没有,请执行-或相应地为ResourceAsStream更新filePath。

答案 1 :(得分:0)

尽管我们的要求随着时间的推移变得越来越复杂,但我之前也曾遇到过同样的问题,但是以下代码可以解决您的问题:

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

    if (cp.exists())
        f = cp.getFile();