我正在尝试从此路径读取相对于存储库根的属性文件夹:
rest/src/main/resources/cognito.properties
我有一个类(class)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;
}
}
但是,当我调用CognitoData
时来自位于 rest/src/test/java/com/bitorb/admin/webapp/security/cognito/CognitoServiceTest.java
的测试类,我收到此错误:
[rest/src/main/resources/cognito.properties (No such file or directory)]
任何人都可以解释为什么会发生这种情况吗?
最佳答案
在这种情况下,文件目录实际上并不是相对的。您需要为此提供适当的文件路径。如果您已经在使用 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")
关于java - 从一个类读取 Java 属性文件时没有这样的文件或目录,但从另一个类读取属性文件时没有这样的文件或目录,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60523076/