getResourceAsStream() is returning null. Properties file is not loading

You are using the class loader (which reads in the classpath) whereas you are using the absolute path.

Simply try:

InputStream resourceAsStream =  new FileInputStream(temp);

As a side note, try instanciating your file doing:

File temp = new File(workingDir, "test.properties");

to use the system-dependent path spearator.


Oh oh ... There are several problems here:

1) In your first provided code snippet, you are using a ClassLoader for loading a resource file. This is indeed a good decision. But the getResourceAsStream method needs a "class-path relative" name. You are providing an absolute path.

2) Your second code snippet (after edit) results in not being able to find the file "D:...\LS360BatchImportIntegration\test.properties". According to your screenshot, the file should be "D:...\LS360AutomatedRegulatorsReportingService\test.properties". This is another directory.

I fear, that your descriptions are not up to date with the findings on your machine.

But let's just move to a reasonable solution:

1) In your Eclipse project (the screenshot tells us, that you are using Eclipse), create a new directory named "resources" in the same depth as your "src" directory. Copy - or better move - the properties file into it.

2) This new directory must be put into the "build path". Right-click the directory in the Package Explorer or Project Explorer view, select "Build Path", then "Use as Source Folder". Note: This build path will be the class path for the project, when you run it.

3) As the resources directory now is part of your class path and contains your properties file, you can simply load it with getResourceAsStream("test.properties").

EDIT

I just see, that you also use Maven (the pom.xml file). In Maven, such a resources directory exists by default and is part of the build path. It is "src/main/resources". If so, just use this.


Please put your property file in /src/main/resources folder and load from ClassLoader. It will be fix.

like

 /src/main/resources/test.properties



Properties properties = null;

try {
    properties = new Properties();
    InputStream resourceAsStream =  Test.class.getClassLoader().getResourceAsStream("test.properties");
    if (resourceAsStream != null) {
        properties.load(resourceAsStream);
    }


} catch (IOException e) {
    e.printStackTrace();
}

Tags:

Java