我对 Java 相当陌生,在将应用程序导出到可运行的 jar 中时遇到问题。 我的应用程序使用 Saxon 运行一些转换,我希望样式表位于可运行的 jar 内。
现在,我的 Eclipse 项目中只有一个子文件夹,并且我正在使用该路径访问样式表。 但是,一旦我将项目导出为该 jar 内的可运行 jar,所有样式表都与使用的库处于同一级别(找不到子文件夹。)
应用程序还在 cwd 中搜索该子文件夹,当然在那里找不到它。
如何打包样式表并在 jar 内正确访问它们?
//更新:
我觉得我还差了一点。
我在 src 下创建了一个子文件夹并将所有样式表放入其中。我像这样访问它们:
xsltexps = comp.compile(new StreamSource(new File(this.getClass().getResource("/stylesheets/" + stylesheets).toURI())));
如果我在 Eclipse 中运行它,一切都会正常。当我将其导出为可运行 jar 并运行它时,出现以下异常:
Exception in thread "main" java.lang.reflect.InvocationTargetException at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source) at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source) at java.lang.reflect.Method.invoke(Unknown Source) at org.eclipse.jdt.internal.jarinjarloader.JarRsrcLoader.main(JarRsrcLoader.java:58)
Caused by: java.lang.IllegalArgumentException: URI is not hierarchical at java.io.File.(Unknown Source)
我不知道这意味着什么。
最佳答案
好的,这就是实际的效果:
xsltexps = comp.compile(new StreamSource(
getClass().getResourceAsStream("/stylesheets/" + stylesheets)));
最重要的变化是使用 getResourceAsStream
而不是 getResource
关于java - 将资源打包成Jar并访问,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18874097/