Search code examples
javaexceptionioexceptionfileinputstream

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?


Solution

  • 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")