我在使用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);
实际上一切都在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/nameWhere 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.