首页 > 解决方案 > 从一个类而不是另一个类中读取 Java 中的属性文件时没有这样的文件或目录

问题描述

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

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;

    }

}

但是,当我CognitoData从位于 的测试类中调用时rest/src/test/java/com/bitorb/admin/webapp/security/cognito/CognitoServiceTest.java,我收到此错误:

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

任何人都可以阐明为什么会这样吗?

标签: javaexceptionioexceptionfileinputstream

解决方案


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

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

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

或者可能在测试期间检查工作目录是什么,看看是否可以将其更改为项目根目录。


推荐阅读