java - 尝试读取资源文件时InputStream为空

标签 java maven

我在/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/

相关文章:

java - GAE 中的 userservicefactory 是否仅适用于拥有 g-mail 帐户的用户?

java - 无法从 https :maven-surefire-plugin:pom:2. maven.apache.org/maven2 传输 org.apache.maven.plugins ://repo. 22.2

maven - 没有这样的字段错误: RESOURCE_PREFIX with a maven project using tess4j

java - Eclipse maven 存储库差异

java - 如何为 ArrayList 中的所有对象调用一个方法?

java - "var"和原始类型如何结合在一起?

java - Maven Mojo : Taking complete control over logging/Forbid other plugins to log

java - org.xml.sax.SAXParseException : Content is not allowed in prolog Problems

java - Maven 'deploy' 导致签名操作后代码重新打包(BAD签名)

javascript - 是否可以使用 Maven 开发前端/Web 应用程序?