简体   繁体   English

获取当前动态Web项目JAVA的路径

[英]Getting the path to current dynamic web project JAVA

How can I access an XML file while my application is already deployed? 应用程序已部署后,如何访问XML文件?

I'm running a Dynamic Web Application with several classes and a simple rest service, but I don't have any actual servlets, so accessing the ServletContext is not possible, (as far as I know) so using getRealPath() won't work. 我正在运行带有多个类和一个简单的Rest服务的Dynamic Web Application,但是我没有任何实际的servlet,因此(据我所知)无法访问ServletContext,因此无法使用getRealPath()工作。

An example: I have a class DBcon which connects to a database, but has to load the properties from an XML file, which are located at /xml/db/oracle-properties.xml 一个示例:我有一个类DBcon,它连接到数据库,但是必须从XML文件中加载属性,该文件位于/xml/db/oracle-properties.xml中。

In a normal Java project you can simply use a file input stream, but it won't work for a dynamic web application. 在普通的Java项目中,您可以仅使用文件输入流,但不适用于动态Web应用程序。

How can I still load the xml file? 我如何仍然可以加载xml文件?

如果文件在类路径中,则可以使用类似以下内容的文件作为输入流:

InputStream in = this.getClass().getResourceAsStream("xml/db/oracle-properties.xml");

I figured out by reading this: Where to place and how to read configuration resource files in servlet based application? 我通过阅读以下内容得出了结论: 在基于Servlet的应用程序中何处放置以及如何读取配置资源文件?

I've put the xml files in WEB-INF/classes and then used this code to load it: 我将xml文件放在WEB-INF / classes中,然后使用以下代码加载它:

InputStream xmlFile = Thread.currentThread().getContextClassLoader().getResourceAsStream(fileName);
    prop.loadFromXML(xmlFile);

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

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