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
  • 79,279
  • 19
  • 185
  • 195
coure2011
  • 40,286
  • 83
  • 216
  • 349

4 Answers4

7

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
  • 79,279
  • 19
  • 185
  • 195
1
String basePath = PropertiesUtil.class.getResource("/").getPath();
InputStream in = new FileInputStream(basePath + "Env.properties");
pros.load(in);

Good luck:)

Hunter Zhao
  • 4,589
  • 2
  • 25
  • 39
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,688
  • 4
  • 23
  • 43
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
  • 3,136
  • 7
  • 32
  • 38