亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

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 關注
  • 162 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號