Vous êtes sur la page 1sur 3

How to read a properties file in a web application

The code to do this is pretty simple. But going by the number of people who keep asking this question, i thought i would post the code over here. Let's consider that you have a war file named SampleApp.war which has a properties file named myApp.properties at it's root :

SampleApp.war | |-------- myApp.properties | |-------- WEB-INF | |---- classes | |----- org |------ myApp |------- MyPropertiesReader.class

Let's assume that you want to read the property named "abc" present in the properties file: ---------------myApp.properties: ---------------abc=some value xyz=some other value

Let's consider that the class org.myApp.MyPropertiesReader present in your application wants to read the property. Here's the code for the same: view plaincopy to clipboardprint? 1. package org.myapp; 2. 3. import java.io.IOException; 4. import java.io.InputStream; 5. import java.util.Properties; 6. 7. /** 8. * Simple class meant to read a properties file 9. * 10. * @author Jaikiran Pai 11. *

12. */ 13. public class MyPropertiesReader { 14. 15. /** 16. * Default Constructor 17. * 18. */ 19. public MyPropertiesReader() { 20. 21. } 22. 23. /** 24. * Some Method 25. * 26. * @throws IOException 27. * 28. */ 29. public void doSomeOperation() throws IOException { 30. // Get the inputStream 31. InputStream inputStream = this.getClass().getClassLoader() 32. .getResourceAsStream("myApp.properties"); 33. 34. Properties properties = new Properties(); 35. 36. System.out.println("InputStream is: " + inputStream); 37. 38. // load the inputStream using the Properties 39. properties.load(inputStream); 40. // get the value of the property 41. String propValue = properties.getProperty("abc"); 42. 43. System.out.println("Property value is: " + propValue); 44. } 45. 46. }

Pretty straight-forward. Now suppose the properties file is not at the root of the application, but inside a folder (let's name it config) in the web application, something like:

SampleApp.war | |-------- config | |------- myApp.properties | | |-------- WEB-INF | |---- classes | |----- org |------ myApp |------- MyPropertiesReader.class

There will just be one line change in the above code: view plaincopy to clipboardprint? 1. public void doSomeOperation() throws IOException { 2. //Get the inputStream-->This time we have specified the folder name too. 3. InputStream inputStream = this.getClass().getClassLoader() 4. .getResourceAsStream("config/myApp.properties"); 5. 6. Properties properties = new Properties(); 7. 8. System.out.println("InputStream is: " + inputStream); 9. 10. //load the inputStream using the Properties 11. properties.load(inputStream); 12. //get the value of the property 13. String propValue = properties.getProperty("abc"); 14. 15. System.out.println("Property value is: " + propValue); 16. } 17.

That's all that is required to get it working.

Vous aimerez peut-être aussi