【问题标题】:Read a file within a jar from java code present in same jar从同一个 jar 中存在的 java 代码读取 jar 中的文件
【发布时间】:2013-01-08 06:02:51
【问题描述】:

我正在尝试使用保存在同一个 jar 中的 java 代码读取保存在 jar 中的 xsd 文件。我正在使用以下代码。

URL tmpurl = ClassLoader.getSystemResource("com/abc/filename.xsd");

Schema s = schemaFactory.newSchema(tmpurl);
jaxbUnMarshaller.setSchema(s);

当我将它作为一个单独的项目运行时它工作正常,但是当我制作一个 jar 时,tmpurl 为空,因此 setSchema 给出了一个空指针异常。

能否请您提供一种解决方法,使其甚至可以在 jar 文件中运行。

【问题讨论】:

    标签: java jar embedded-resource


    【解决方案1】:

    你试过了吗?

    getClass().getClassLoader().getResource()
    

    你在 jar 清单文件中的 classpath 也很重要。

    请在此处查看已接受的答案:

    Class.getResource and ClassLoader.getSystemResource: is there a reason to prefer one to another?

    Loading files with ClassLoader

    【讨论】:

    • 谢谢,工作完美,无论你指出什么都是绝对正确的,并且给定的链接也很有帮助和信息量。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-10-07
    • 2015-06-15
    • 1970-01-01
    • 2018-06-04
    • 2011-03-23
    相关资源
    最近更新 更多