簡體   English   中英

從一個類而不是另一個類讀取 Java 中的屬性文件時沒有這樣的文件或目錄

[英]No such file or directory when reading Properties File in Java from one Class but not another

我正在嘗試從此路徑讀取與存儲庫根相關的屬性文件夾:

rest/src/main/resources/cognito.properties

我有一個來自此路徑的CognitoData類: rest/src/main/java/com/bitorb/admin/webapp/security/cognito/CognitoData.java使用此代碼加載 Properties 文件夾,並且運行良好:

new CognitoProperties().loadProperties("rest/src/main/resources/cognito.properties");
@Slf4j
public class CognitoProperties {

    public  Properties loadProperties(String fileName) {

        Properties cognitoProperties = new Properties();

        try {
            @Cleanup
            FileInputStream fileInputStream = new FileInputStream(fileName);
            cognitoProperties.load(fileInputStream);
        } catch (IOException e) {
            log.error("Error occured. Exception message was [" + e.getMessage() + "]");
        }

        return cognitoProperties;

    }

}

但是,當我從位於rest/src/test/java/com/bitorb/admin/webapp/security/cognito/CognitoServiceTest.java的測試類調用CognitoData時,我收到此錯誤:

[rest/src/main/resources/cognito.properties (No such file or directory)]

任何人都可以解釋為什么會發生這種情況嗎?

我不知道您使用什么進行測試,但我懷疑運行測試時的工作目錄不是項目根目錄。

一種解決方案是使用絕對路徑:

/absolute/path/to/project/rest/src/main/resources/cognito.properties

或者在測試期間檢查工作目錄是什么,看看它是否可以更改為項目根目錄。

在這種情況下,文件目錄實際上不是相對的。 您需要為此提供適當的文件路徑。 如果您已經在使用 spring boot,那么您可以將代碼更改為:

// this will read file from the resource folder.
InputStream inputStream = getClass().getClassLoader()
                          .getResourceAsStream("cognito.properties");

cognitoProperties.load(inputStream);

否則,您需要提供完整的絕對路徑。 new CognitoProperties().loadProperties("/absolutepath/..../cognito.properties")

暫無
暫無

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

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