Parse XML File within Jar

2019-08-19 05:36发布

问题:

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.