简体   繁体   中英

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());
    }

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

Eg 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();

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM