2

I have a properties file at location (from netbeans project explorer)

-MyTest
    +Web Pages
    +Source Packages
    -Test Packages
        -<default package>
            +Env.properties     <---- Here it is
        +com.mycomp.gts.test
        +com.mycomp.gts.logintest
        .....
        ....

Now when I am trying to find this file using code

InputStream propertiesInputStream = getClass().getResourceAsStream("Env.properties");
ENV.load(propertiesInputStream);

Its throwing java.lang.NullPointerException

Perception
  • 77,470
  • 19
  • 176
  • 187
coure2011
  • 37,153
  • 75
  • 206
  • 328

4 Answers4

6

You cannot use the class as a reference to load the resource, because the resource path is not relative to the class. Use the class loader instead:

InputStream propertiesInputStream = getClass().getClassLoader()
        .getResourceAsStream("Env.properties");
ENV.load(propertiesInputStream);

Or alternatively, you can use the context class loader of the current thread:

InputStream propertiesInputStream = Thread.currentThread()
    .getContextClassLoader().getResourceAsStream("Env.properties");
ENV.load(propertiesInputStream);
Perception
  • 77,470
  • 19
  • 176
  • 187
1
String basePath = PropertiesUtil.class.getResource("/").getPath();
InputStream in = new FileInputStream(basePath + "Env.properties");
pros.load(in);

Good luck:)

Hunter Zhao
  • 4,429
  • 1
  • 23
  • 38
1

Try to get absolute path with:

String absolute = getClass().getProtectionDomain().getCodeSource().getLocation().toExternalForm();

You can print out the string absolute and try to substring it to your path of your properties file.

sk2212
  • 1,618
  • 4
  • 22
  • 42
0

The below code reads a property file stored within the resources folder of a Maven project.

InputStream inputStream = YourClass.class.getResourceAsStream("/filename.properties");
BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream))) {
    
Properties properties = new Properties();
properties.load(reader);
  
} catch (IOException ioException) {
    ioException.printStackTrace();
}
Elletlar
  • 2,991
  • 7
  • 29
  • 34