26

I am trying to load properties file. Here is my structure

Directory Structure

Now i am trying to load test.properties file. But i am getting null. Here how i am doing

public class Test {

    String workingDir = System.getProperty("user.dir");
    System.out.println("Current working directory : " + workingDir);

    File temp = new File(workingDir + "\\" + "test.properties");
    String absolutePath = temp.getAbsolutePath();
    System.out.println("File path : " + absolutePath);

    Properties properties = null;

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


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

    System.exit(0);

} //end of class Test

This program prints

Current working directory : D:\Personal Work\eclipse 32 Bit\workspace\Spring Integration\LS360BatchImportIntegration
File path : D:\Personal Work\eclipse 32 Bit\workspace\Spring Integration\LS360BatchImportIntegration\test.properties

But it is not loading properties file from this path. Although it is present there. Why i am getting null ?

Thanks

Edit--- ----------------------------

String workingDir = System.getProperty("user.dir");
System.out.println("Current working directory : " + workingDir);

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

String absolutePath = temp.getAbsolutePath();
System.out.println("File path : " + absolutePath);

try {
    properties = new Properties();
    InputStream resourceAsStream =  new FileInputStream(temp);
    if (resourceAsStream != null) {
        properties.load(resourceAsStream);
    }   
} catch (IOException e) {
    e.printStackTrace();
}

System.exit(0);

Current working directory : D:\Personal Work\eclipse 32 Bit\workspace\Spring Integration\LS360BatchImportIntegration
File path : D:\Personal Work\eclipse 32 Bit\workspace\Spring Integration\LS360BatchImportIntegration\test.properties
java.io.FileNotFoundException: D:\Personal Work\eclipse 32 Bit\workspace\Spring Integration\LS360BatchImportIntegration\test.properties (The system cannot find the file specified)
at java.io.FileInputStream.open(Native Method)
at java.io.FileInputStream.<init>(Unknown Source)
at com.softech.ls360.integration.BatchImport.main(BatchImport.java:57)
Basit
  • 8,426
  • 46
  • 116
  • 196

6 Answers6

29

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.

Seelenvirtuose
  • 20,273
  • 6
  • 37
  • 66
  • Yes i found that i copy the `test.proeprties` file in wrong place. Now it is loading from stream after putting it in right place :). Yes i am using maven. You mean move properties file to `src/main/resources` folder. And add `src/main/resources` folder to class path by right clicking as you said (point 2) ? – Basit Aug 05 '13 at 10:13
  • I think `src/main/resources` is already on class path in maven .. ? – Basit Aug 05 '13 at 10:15
  • @Basit: Exactly. "src/main/resources" is the Maven default directory for such resources. If you use Maven to package your application, it will be considered automatically (and become part of your JAR). If you run the project in Eclipse, the M2E plugin takes care of that. – Seelenvirtuose Aug 05 '13 at 11:24
  • yes it is loading after putting it in `src/main/resources`. One thing that i want to do when jar is made then properties file is included in the jar, i don't want to included it in the jar, i have done it using maven, but i stuck after moving it from jar how can i instruct my jar to read properties file. If i open my jar, then my properties file is at root of jar. – Basit Aug 05 '13 at 12:00
  • Very nice explanation, I am trying with `Thread.currentThread().getContextClassLoader().getResourceAsStream("myfile.properties")` it is giving me null. Could you please explain this behaviour and operations behind the scenes like the above answer. – Shivkumar Mallesappa May 04 '18 at 10:33
15

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();
}
Mukhtiar Ahmed
  • 611
  • 4
  • 12
  • ok, after putting in resources folder then just use `InputStream resourceAsStream = BatchImport.class.getResourceAsStream("test.properties");`. Is it ? – Basit Aug 05 '13 at 10:22
  • 1
    Yes, Becasue ClassLoader search file in class path – Mukhtiar Ahmed Aug 05 '13 at 10:27
  • After numerous attempt, finally got it to work, remember to do a clean and build only then it will update the correct path – GoodJeans Mar 01 '19 at 13:08
10

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.

Jean Logeart
  • 52,687
  • 11
  • 83
  • 118
  • 1
    i am getting exception. File not found exception why ? Here i used this `InputStream resourceAsStream = new FileInputStream(temp);`. Properties file is present there. You can see it in the output ...? – Basit Aug 05 '13 at 08:03
  • Actually, your ``workingDir`` is not the one containing the properties! Your properties is in ``LS360AutomatedRegulatorsReportingService`` while the code returns ``LS360BatchImportIntegration`` – Jean Logeart Aug 05 '13 at 10:23
  • yes i figured out that , and now it is loading :). Actually i am making jar, and i want that after making jar, properties file, not included in the jar, otherwise even for testing i need to again create the jar. So i want that i put my properties file in a place where after making jar i can point pout my jar to read properties file from there. I am creating jar using maven. – Basit Aug 05 '13 at 10:26
1

I had a similar problem with a file not being found by getResourceAsStream(). The file was in the resources folder (src/main/resources), and still not found.

The problem got resolved when I went into the eclipse Package Explorer and "refreshed" the resources folder. It was in the directory, but Eclipse did not see it until the folder was refreshed (right-click on the folder and select Refresh).

Diligent Key Presser
  • 4,183
  • 4
  • 26
  • 34
SusanGHP
  • 11
  • 1
  • 3
1

I hope this helps !! You can keep your test.properties into src/main/resources

 public static Properties props = new Properties();
    InputStream inStream = Test.class.getResourceAsStream("/test.properties");
    try {
            loadConfigurations(inStream);
        } catch (IOException ex) {
            String errMsg = "Exception in loading configuration file. Please check if application.properties file is present in classpath.";
            ExceptionUtils.throwRuntimeException(errMsg, ex, LOGGER);
        }
    public static void loadConfigurations(InputStream inputStream) throws IOException{
            props.load(inputStream);
        }
0

You're passing a file path to getResourceAsStream(String name), but name here is a class path, not a file path...

You could make sure the file is on your classpath, or use a FileInputStream instead.

MattR
  • 6,908
  • 2
  • 21
  • 30