我在/src/main/resources
中有一个JSON文件我试图通过以下方式阅读:
private List<String> readContextFromFile(String file) {
List<String> context = new ArrayList<>();
try {
InputStream in = getClass().getClassLoader().getResourceAsStream(file);
Map<String, ArrayList> input = objectMapper.readValue(in, HashMap.class);
context = input.get("@context");
} catch (IOException e) {
LOGGER.error("Error reading value {}", e.getMessage());
}
return context;
}
但是,InputStream 为空。
这是我传递的文件路径:/resources/context.json
我做错了什么?
最佳答案
1) /src/main/resources
表示源代码,而不是运行时代码。
编译的类和处理的资源结束于 target/classes
文件夹,而不是 src
文件夹。
2)关于:
This is the file path that I pass:
/resources/context.json
为什么要传递resources
token ?它是一个 Maven/Gradle 目录,您在运行时不会检索该目录。只有其中包含的内容才会在运行时可用。
您要传递的是 /context.json
。
关于java - 尝试读取资源文件时InputStream为空,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57107430/