Parse XML File within Jar

[亡魂溺海] 提交于 2019-12-25 00:16:08

问题


I am having troubles loading an XML file within my java game. Here is where the file is located, (from Eclipse):

I have been doing research, and apparently to use the xml file in a JAR file, I need to call

DocumentBuilder.parse(InputStream)

The problem is when I try to get the InputStream using getResourceAsStream("res/xml/items.xml") it always returns null.

How could I make it not return null? I don't want to put my res folder inside of my "src" folder, but is there some setting in Eclipse that I need to set? What would the correct String of the path be? Thanks!

Edit:

My code:

try {
    DocumentBuilder db = dbf.newDocumentBuilder();
    InputStream is = Thread.currentThread().getContextClassLoader().getResourceAsStream("res/xml/items.xml");
    dom = db.parse(is);
} catch(Exception e) {
    e.printStackTrace();
}

This still gives me null.


回答1:


So, assuming that you tell Eclipse to use "res" as a source folder, you still have two problems with your lookup:

Item.class.getResourceAsStream("res/xml/items.xml");

This is a relative path, so getResourceAsStream() will prepend the directory where Item.class lives (see docs).

The second problem is that Eclipse treats "source" folders as the root of your classpath. So you need to change the paths to exclude "res".

One option is to use an absolute path: "/xml/items.xml"

A better option is to call Thread.currentThread().getContextClassLoader().getResourceAsStream(), which will work correctly in an app-server as well as in a self-contained application (and is a good habit to get into). But you still need to omit "res" from your path.



来源:https://stackoverflow.com/questions/15535153/parse-xml-file-within-jar

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!