Reputation:
I Created a REST Web Service in Which I Created a config.properties file to store and retrieve some usernames and passwords through out the application. I stored it in /src/main/resources/config.properties.
when I tried to load it from my java code from eclipse it's working fine. but when I deployed it in tomcat it's not loading. the code i'm using to load the properties file is
properties.load(new FileInputStream("src/main/resources/config.properties"));
Can anyone help me how to resolve that issue
Upvotes: 13
Views: 26922
Reputation: 1290
Suppose you want to read a example.properties file located in /WEB-INF/props/example.properties in run time.
Properties properties = new java.util.Properties();
InputStream inputStream =
getServletContext().getResourceAsStream("/WEB-INF/props/example.properties");
properties.load(inputStream);
Now , we are ready to get value from example.properties file .
String value = properties.getProperty("propertyName");
Sample Properties File :
example.properties
propertyName = 123
Upvotes: 1
Reputation: 45090
Try to load it from the classpath:-
final Properties properties = new Properties();
properties.load(this.getClass().getResourceAsStream("/config.properties"));
Upvotes: 1
Reputation: 40358
You can easily do it if your properties file is in WEB-INF/classes. In this case just write something like
Properties props = new Properties();
props.load(getClass().getResourceAsStream("/name.properties"));
Obviously the file may be located in sub folder of classes. In this case you have to specify the full path when calling getResourceAsStream()
Upvotes: 3
Reputation: 692231
What you deploy to Tomcat is a war file. Tomcat doesn't know or care about the directory where the sources of your application are.
The files in src/main/resources
are copied to the target/classes
directory by Maven, and this directory is then copied to the WEB-INF/classes
directory of the deployed web application, which is in the classpath of your webapp. So you just need to load the file using the class loader:
properties.load(MyClass.class.getResourceAsStream("/config.properties"));
(MyClass being any class of your webapp).
Upvotes: 32