如何从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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
您需要将 XML 磁贴的(JAR 相对)路径添加到
MANIFEST.MF
文件中的Class-Path
条目。此条目包含有关 JAR 运行时类路径的信息。假设您希望将 XML 与 JAR 文件本身放在同一文件夹中,则以下内容就足够了:(不要忘记在
MANIFEST.MF
末尾添加一个空行文件)然后您可以使用
Class#getResource()
或ClassLoader#getResource()
。对于你的情况,第一个就足够了。You need to add the (JAR-relative) path to the XML tile to the
Class-Path
entry in theMANIFEST.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:(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()
orClassLoader#getResource()
. The first suffices in your case.将该文件添加到 JAR 清单中的类路径并将其作为输入流读取。
Add that file to the class path in your JAR manifest and read it as an input stream.
你可以试试这个:
获取可执行文件之外的相对路径罐子
You could try this :
Obtaining relative path outside of executable JAR
应该给你 jar 路径。将其打印出来进行仔细检查,然后在其上构建相对路径。
Should give you the jar path. Print it out to double check, and then build your relative path onto it.
如果不知道您正在运行什么操作系统,则很难给出准确的答案。
一般的答案是修改您的启动器(桌面上的图标),以便将初始工作目录指定为与从 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.