[英]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.