簡體   English   中英

Spring / Maven 從類路徑加載文件

[英]Spring / Maven load file from classpath

在我的資源文件夾中:

src/main/resources

我有兩個文件application.properties文件和 JSON 文件app.schema.json

我有以下 function:

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 package
  • java -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>

兩種方式都行不通。 It can reach the file if I run mvn spring-boot:run but also if I run mvn clean package spring-boot:repackage and java -jar target/app.jar It doesnt find the file.

我檢查了所有文檔並嘗試了幾種不同的方法來加載文件,但無論哪種方式都找不到它。

我怎樣才能使文件可用?

您需要使用其相對路徑將src/main/resources目錄包含到 pom.xml 中的類路徑中:

 <build>
    <resources>
        <resource>
            <directory>src/main/resources</directory>
        </resource>
    </resources>
 </build>

你可以在這里閱讀更多關於它的信息。

你能否檢查一下 jar 里面是否包含 classes 文件夾中提到的文件。 您也可以嘗試下面的代碼從類路徑加載文件。

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

如果可能,則將該文件保留在 jar 之外的某個文件夾位置,並在執行 jar 時將該位置設置為類路徑。

正如 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 架構,因此我需要將 Inputstream 轉換為閱讀器 object

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM