解析 Jar 中的 XML 文件 [英] Parse XML File within Jar

查看:58
本文介绍了解析 Jar 中的 XML 文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在我的 Java 游戏中加载 XML 文件时遇到问题.这是文件所在的位置,(来自 Eclipse):

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

我一直在研究,显然要在JAR文件中使用xml文件,我需要调用

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

DocumentBuilder.parse(InputStream)

问题是当我尝试使用 getResourceAsStream("res/xml/items.xml") 获取 InputStream 时它总是返回 null.

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

我怎样才能让它不返回空值?我不想将我的 res 文件夹放在我的src"文件夹中,但是我需要在 Eclipse 中设置一些设置吗?路径的正确字符串是什么?谢谢!

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!

我的代码:

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

这仍然给我空.

推荐答案

因此,假设您告诉 Eclipse 使用res"作为源文件夹,您的查找仍然存在两个问题:

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");

这是一个相对路径,所以 getResourceAsStream() 将在 Item.class 所在的目录前面加上(参见 docs).

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

第二个问题是 Eclipse 将源"文件夹视为类路径的根.因此,您需要更改路径以排除res".

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".

一种选择是使用绝对路径:"/xml/items.xml"

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

更好的选择是调用 Thread.currentThread().getContextClassLoader().getResourceAsStream(),它可以在应用服务器和自包含应用程序中正常工作(和养成好习惯).但是你仍然需要从你的路径中省略res".

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.

这篇关于解析 Jar 中的 XML 文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆