繁体   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