Reputation: 42394
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
Upvotes: 2
Views: 23310
Reputation: 1
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();
}
Upvotes: 0
Reputation: 1722
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.
Upvotes: 1
Reputation: 4649
String basePath = PropertiesUtil.class.getResource("/").getPath();
InputStream in = new FileInputStream(basePath + "Env.properties");
pros.load(in);
Good luck:)
Upvotes: 1
Reputation: 80593
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);
Upvotes: 7