简体   繁体   English

如何获取运行时Web应用程序路径?

[英]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. 在我的Web应用程序中,我在web文件夹中使用属性文件,我需要从同一应用程序中的java文件中引用属性文件以获取属性的值。 How can I provide the path? 我该如何提供路径? I need the path name and not the URI. 我需要路径名而不是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. 考虑到它是一个属性文件,我建议您从类路径中将其作为ResourceBundle获取。

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对象:

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. 这样你真的不需要servlet和web应用程序的路径。 The above method will look for the resource in the classpath. 上面的方法将在类路径中查找资源。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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