Developer404
Developer404

Reputation: 5962

How to get Runtime Web Application path?

In my web application, I'm using property file inside web folder and I need to refer the property file from java file in the same application to get the value of the property. How can I provide the path? I need the path name and not the URI. My code is as follows:

    Properties prop = new Properties();
    FileInputStream propertiesStream = null;
    try {
        propertiesStream = new FileInputStream("..\Files\Prop.properties");
        prop = new Properties();
        prop.load(propertiesStream);
        prop.getProperty("id");
        propertiesStream.close();
    } catch (IOException ioException) {
        System.out.println("PropertiesLoader IOException message:" + ioException.getMessage());
    }

Upvotes: 1

Views: 2435

Answers (2)

Allan Lykke Christensen
Allan Lykke Christensen

Reputation: 1347

Considering that it is a properties file I would suggest that you fetch it as a ResourceBundle from your classpath.

E.g. say you put your properties file here:

/WEB-INF/classes/MyProperties.properties

You could fetch it with the following code:

ResourceBundle props = ResourceBundle.getBundle("MyProperties");

Or as a Properties object:

Properties props = new Properties();
InputStream is = getClass().getResourceAsStream("MyProperties");
props.load(is);
is.close();

Upvotes: 3

Pushkar
Pushkar

Reputation: 7580

If you want to read the properties file in your package then you should use -

InputStream is = pageContext.getServletContext().getResourceAsStream("/props/env- props.properties");
BufferedReader reader = new BufferedReader(is);

After getting the buferred reader you can manipulate it as you want to. This way you really dont need the path of the servlet and the web application. The above method will look for the resource in the classpath.

Upvotes: 1

Related Questions