如何从jar读取外部xml文件 [英] How to read external xml file from jar

查看:205
本文介绍了如何从jar读取外部xml文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要在jar可执行文件中从我的java应用程序中读取外部XML文件。

如果我从控制台(java -jar package.jar)午餐它可以正常工作,但如果我午餐的话通过双击(Java Platform SE二进制)它不起作用。

我有相对路径的这个问题。
使用绝对路径它可以双向工作。

i need to read an external XML file from my java application in jar executable file.
If I lunch it from console (java -jar package.jar) it works fine, but if I lunch it by double click (Java Platform SE binary) it don't work.
I have this problem with relative path. With absolute path it work in both way.

推荐答案

您需要添加(JAR相对)路径到XML磁贴到 MANIFEST.MF 文件中的 Class-Path 条目。此条目包含有关JAR运行时类路径的信息。假设您希望将XML与JAR文件本身放在同一文件夹中,以下内容就足够了:

You need to add the (JAR-relative) path to the XML tile to the Class-Path entry in the MANIFEST.MF file. This entry contains information about the JAR's runtime classpath. Assuming that you'd like to have the XML in the same folder as the JAR file itself, the following suffices:

Class-Path: .

(别忘了在 MANIFEST.MF 文件)

然后您可以使用 Class#getResource( ) ClassLoader#getResource() 。第一个就足够了。

Then you can obtain it as a classpath resource using Class#getResource() or ClassLoader#getResource(). The first suffices in your case.

URL xmlResource = getClass().getResource("/filename.xml");
File xmlFile = new File(xmlResource.getPath());
// ...

这篇关于如何从jar读取外部xml文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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