简体   繁体   中英

No such file or directory when reading Properties File in Java from one Class but not another

I am trying to read a properties folder from this path with respect to the repository root:

rest/src/main/resources/cognito.properties

I have a Class CognitoData from this path: rest/src/main/java/com/bitorb/admin/webapp/security/cognito/CognitoData.java which loads the Properties folder using this code, and it runs fine:

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;

    }

}

However, when I call CognitoData from a test class located in rest/src/test/java/com/bitorb/admin/webapp/security/cognito/CognitoServiceTest.java , I get this error:

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

Can anybody shed light on why this is happening?

I don't know what you're using for testing, but I suspect that the working directory when you run tests is not the project root.

One solution is to use an absolute path instead:

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

Or maybe check what is the working directory during testing and see if it can be changed to the project root.

File directory is not actually relative in that case. You need to provide appropriate file path for this. If you are already using spring boot, then you can change your code to:

// this will read file from the resource folder.
InputStream inputStream = getClass().getClassLoader()
                          .getResourceAsStream("cognito.properties");

cognitoProperties.load(inputStream);

Otherwise you need to provide the full absolute path. new CognitoProperties().loadProperties("/absolutepath/..../cognito.properties")

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM