Reputation: 505
I want to read a line from properties file called jdbc.properties. It locate in src\main\webapp\WEB-INF\db\jdbc.properties
. What path should I use?
This is my method:
Properties prop = new Properties();
try {
// load a properties file
prop.load(new FileInputStream("jdbc.properties"));
System.out.println(prop.getProperty("password"));
} catch (IOException ex) {
ex.printStackTrace();
}
Upvotes: 0
Views: 5984
Reputation: 280138
If you move your properties file to src/main/resources
, assuming your project is managed by maven, then you could retrieve it by doing
Properties prop = new Properties();
try {
// load a properties file
prop.load(YourClass.class.getResourceAsStream("/jdbc.properties")); // note the leading /
System.out.println(prop.getProperty("password"));
} catch (IOException ex) {
ex.printStackTrace();
}
where YourClass
is whatever class this code is in.
Maven places the class files of your compiled classes and all resources in src/main/resources
in WEB-INF/classes
where only your application can access them.
If you put the file in src/main/resources/someFolder
, you'll need to access it from
prop.load(YourClass.class.getResourceAsStream("/someFolder/jdbcProperties"));
The path you provide to the above method is relative to the package of the class you are in, unless you specify a leading forward-slash, in which case it will be relative to the root of the classpath, ie classes
folder.
Upvotes: 6
Reputation: 3719
Is environment variable set for TOMCAT_HOME, if not set it up.
Now you can use
<tomcat_home>/webapps/<yourapp>/web-inf/db/jdbc.properties
To get value of environment variable use following code:
Map<String, String> env = System.getenv();
Cheers !!
Upvotes: 0
Reputation: 597342
You need to specify an absolute path to the FileInputStream
. You can get the path by calling servletContext.getRealPath("/WEB-INF/db/jdbc.properties")
If you do not have the servletContext
available (via .getServletContext()
), then you should pass it (or the absolute path to the root of the app) to the code above.
Upvotes: 2