如何从jar中读取外部xml文件

发布于 2024-09-17 20:47:51 字数 166 浏览 6 评论 0原文

我需要从 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.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(5

长伴 2024-09-24 20:47:51

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

Class-Path: .

(不要忘记在 MANIFEST.MF 末尾添加一个空行文件)

然后您可以使用 Class#getResource()ClassLoader#getResource()。对于你的情况,第一个就足够了。

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

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

(don't forget to put a blank line at end of MANIFEST.MF file)

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());
// ...
能怎样 2024-09-24 20:47:51

将该文件添加到 JAR 清单中的类路径并将其作为输入流读取。

Add that file to the class path in your JAR manifest and read it as an input stream.

冰葑 2024-09-24 20:47:51
(new File(".")).getAbsolutePath();

应该给你 jar 路径。将其打印出来进行仔细检查,然后在其上构建相对路径。

(new File(".")).getAbsolutePath();

Should give you the jar path. Print it out to double check, and then build your relative path onto it.

薄荷→糖丶微凉 2024-09-24 20:47:51

如果不知道您正在运行什么操作系统,则很难给出准确的答案。

一般的答案是修改您的启动器(桌面上的图标),以便将初始工作目录指定为与从 shell 运行命令时使用的目录相同。

It's hard to give a precise answer without knowing what OS you are running.

The general answer would be to modify your launcher (the icon on the desktop) in order to specify the initial working directory to be the same as the one you use when you run the command from a shell.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文