简体   繁体   中英

Parse XML File within Jar

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

Eclipse IDE中的软件包浏览器

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.

在此处输入图片说明

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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