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服务的动态Web应用程序,但是我没有任何实际的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 /db/oracle- property . XML的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文件?
2 个解决方案
#1
3
If the file is in the classpath, you can get it as input stream with something like this:
如果文件在类路径中,您可以将其作为输入流,如下所示:
InputStream in = this.getClass().getResourceAsStream("xml/db/oracle-properties.xml");
#2
1
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/类中,然后使用此代码加载:
InputStream xmlFile = Thread.currentThread().getContextClassLoader().getResourceAsStream(fileName);
prop.loadFromXML(xmlFile);
#1
3
If the file is in the classpath, you can get it as input stream with something like this:
如果文件在类路径中,您可以将其作为输入流,如下所示:
InputStream in = this.getClass().getResourceAsStream("xml/db/oracle-properties.xml");
#2
1
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/类中,然后使用此代码加载:
InputStream xmlFile = Thread.currentThread().getContextClassLoader().getResourceAsStream(fileName);
prop.loadFromXML(xmlFile);