从一个类而不是另一个类中读取Java中的属性文件时,没有这样的文件或目录

问题描述 投票:0回答:2

我正在尝试从此路径相对于存储库根目录读取属性文件夹:

rest/src/main/resources/cognito.properties

我在以下路径中有一个类CognitoDatarest/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)]

有人可以阐明为什么会这样吗?

java exception ioexception fileinputstream
2个回答
0
投票

我不知道您正在使用什么进行测试,但是我怀疑运行测试时的工作目录不是项目根目录。

一种解决方案是改用绝对路径:

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

或者也许在测试过程中检查工作目录是什么,看看是否可以将其更改为项目根目录。


0
投票

在这种情况下,文件目录实际上不是相对的。您需要为此提供适当的文件路径。如果您已经在使用Spring Boot,那么new CognitoProperties().loadProperties("cognito.properties")就足够了。否则,您需要提供完整的绝对路径。 new CognitoProperties().loadProperties("/absolutepath/..../cognito.properties")

© www.soinside.com 2019 - 2024. All rights reserved.