为了账号安全,请及时绑定邮箱和手机立即绑定

Spring / Maven 从类路径加载文件

Spring / Maven 从类路径加载文件

萧十郎 2024-01-28 15:54:57
在我的资源文件夹中:src/main/resources我有两个文件,一个application.properties文件和一个 JSON 文件app.schema.json我有以下功能:private File loadSchema(String schemaName) throws JsonSchemaMissingException {        ClassLoader classLoader = JsonSchemaValidator.class.getClassLoader();        File file = new File(Objects.requireNonNull(classLoader.getResource("app.schema.json")).getFile());        if (!file.exists()) {            log.LogErrorWithTransactionId("", "file does not exist " + file.getAbsolutePath());            throw new JsonSchemaMissingException("file does not exist");        }        return file;    }如果我运行mvn spring-boot:run它成功找到该文件。如果我运行:mvn packagejava -jar app.jar我得到一个NullPointer,因为以下文件不存在:/home/XXX/Docs/project/XXX/file:/home/ghovat/Docs/project/XXX/target/app.jar!/BOOT-INF/classes!/app.event.json在构建中的 pom.xml 中,我添加了以下设置:<resources>            <resource>                <directory>src/main/resources</directory>            </resource>        </resources>无论哪种方式都行不通。如果我运行,它可以到达该文件mvn spring-boot:run ,但如果我运行mvn clean package spring-boot:repackage但java -jar target/app.jar找不到该文件,它也可以到达该文件。我检查了所有文档并尝试了几种不同的方法来加载文件,但无论哪种方式都找不到它。我怎样才能使该文件可用?
查看完整描述

3 回答

?
元芳怎么了

TA贡献1798条经验 获得超7个赞

您能否检查一下 jar 内是否包含类文件夹中提到的文件。您也可以尝试下面的代码从类路径加载文件。

Thread.currentThread().getContextClassLoader().getResource(<file_name>)

如果可能,则将该文件保留在 jar 外部的某个文件夹位置,并在执行 jar 时将该位置设置为类路径。


查看完整回答
反对 回复 2024-01-28
?
胡子哥哥

TA贡献1825条经验 获得超6个赞

您需要src/main/resources使用其相对路径将目录包含到 pom.xml 中的类路径中:


 <build>

    <resources>

        <resource>

            <directory>src/main/resources</directory>

        </resource>

    </resources>

 </build>

你可以在这里读更多关于它的内容。



查看完整回答
反对 回复 2024-01-28
?
www说

TA贡献1775条经验 获得超8个赞

正如 Ropert Scholte 提到的修复它一样,我使用 Inputstream 来加载,而不是将其作为文件加载。我用下面的代码修复了它:


private Reader loadSchema(String schemaName) throws JsonSchemaMissingException {

    ClassLoader classLoader = JsonSchemaValidator.class.getClassLoader();

    InputStream fileStream = classLoader.getResourceAsStream(schemaName);


    if (fileStream == null) {

        log.LogErrorWithTransactionId("", "file does not exist ");

        throw new JsonSchemaMissingException("file does not exist");

    }

    Reader reader = new InputStreamReader(fileStream, StandardCharsets.UTF_8);

    return reader;

}

请注意,由于我使用该文件来验证 JSON 架构,因此我需要将输入流转换为读取器对象


查看完整回答
反对 回复 2024-01-28
  • 3 回答
  • 0 关注
  • 30 浏览

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信