使用docker容器中的java访问类路径中的JSON文件时遇到FileNotFoundException(SprintBootApplication)

前端之家收集整理的这篇文章主要介绍了使用docker容器中的java访问类路径中的JSON文件时遇到FileNotFoundException(SprintBootApplication)前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。

我在使用docker容器加载Java jar类路径中的JSON文件时遇到FileNotFoundException,它是一个Spring-Boot应用程序.此JSON文件在资源文件夹中可用.我能够在./target/classes/path下的docker中看到JSON文件.

Resource resource = resourceLoader.getResource("classpath:folderNm/file.json");
HashMap

但是我得到了这个例外:

java.io.FileNotFoundException: class path resource [folderNm/file.json] cannot be resolved to absolute file path because it does not reside in the file system: jar:file:/app.jar!/folderNm/file.json

我试过了

– > resource.getFile()的getPath();
– > resource.getFile()getCanonicalPath();
– > “./target/classes/folderName/fileName”(硬编码的FilePath位置)
– > “/app.jar!/folderNm/file.json”(硬编码的FilePath位置)

InputStream inputStream = getClass().getResourceAsStream("xyz.json");
BufferedReader br = new BufferedReader(new InputStreamReader(inputStream,"UTF-8"));
            StringBuilder responseStrBuilder = new StringBuilder();
            String inputStr;
            while ((inputStr = br.readLine()) != null)
                responseStrBuilder.append(inputStr);

以上都没有运行.请建议一种解决此问题的方法.

最佳答案
假设在maven结构中(你正在使用maven,对吗?)你的文件位于src / main / resources / folderName / file.json,你传递给getResourceAsStream的路径应该是/folderName/file.json

实际上一切都在javadocs中解释:

Before delegation,an absolute resource name is constructed from the
given resource name using this algorithm:

  • If the name begins with a ‘/’ (‘\u002f’),then the absolute name of
    the resource is the portion of the name following the ‘/’.
  • Otherwise,
    the absolute name is of the following form: modified_package_name/name

Where the modified_package_name is the package name of this object
with ‘/’ substituted for ‘.’ (‘\u002e’).

基本上,如果你跳过前面的’/’,它会在你的类的包中查找folderName.以下代码对我来说很好:

    InputStream inputStream = StackTest.class.getResourceAsStream("/folderName/file.json");
    BufferedReader br = new BufferedReader(new InputStreamReader(inputStream,"UTF-8"));
    StringBuilder responseStrBuilder = new StringBuilder();
    String inputStr;
    while ((inputStr = br.readLine()) != null)
        responseStrBuilder.append(inputStr);
    System.out.println(responseStrBuilder.toString());

假设我在src / main / resources / folderName中有我的file.json.我不认为它与docker有任何关系.
顺便说一下,我想你可以利用Apache Commons IOUtils.toString来帮助将InputStream变成一个String.

原文链接:https://www.f2er.com/docker/436643.html

猜你在找的Docker相关文章