【问题标题】:How to get a file that it is inside my jar file? [duplicate]如何获取它在我的 jar 文件中的文件? [复制]
【发布时间】:2021-09-13 13:30:40
【问题描述】:

我需要访问我的 jar 中的 xsd 文件。我的问题是我的类路径是 C:\Users\fabio\Documents

我的jar文件也在那个路径下,那我怎么才能得到我需要的文件呢?

我尝试了 File xsdFile=new File(String.valueOf(MigrationsApplication.class.getResource("DBRegister.xsd")));,但收到此错误消息 schema_reference.4: Failed to read schema document 'file:/C:/Users/fabio/Documents/null', because 1) could not find the document; 2) the document could not be read; 3) the root element of the document is not <xsd:schema>.

这是我需要的 xsd 文件的位置

【问题讨论】:

    标签: java file jar getresource


    【解决方案1】:

    MigrationsApplication.class.getResource("DBRegister.xsd")

    这部分很好。

    new File

    不。文件是指硬盘上的实际文件。而那个资源不是其中之一。您不能在此处使用 File。期间。

    读取资源的API只有两个:

    • InputStream 或其他一些抽象源概念(例如URL)一起工作的那些。也许除了(例如重载方法)接受FilePath 或(糟糕的设计)String 代表文件路径的方法。
    • 你不应该使用的垃圾。

    希望您拥有第一种 API :)

    然后我们修复一些错误:

    1. 使用getResourceAsStream 获取InputStream,getResource 获取URL。你应该使用哪一个?好吧,检查您将此资源传递到何处的 API。例如,swing 的 ImageIcon 接受 URL,因此您将在此处使用 getResource
    2. .getResource("DBRegister.xsd")MigrationsApplication.class 所在的同一位置查找该文件。哪条路是错的!您的 DBRegister.xsd 在“根”中。在开头包含一个斜杠以相对于根进行解析。

    很容易照顾它:

    try (var in = MigrationsApplication.class.getResourceAsStream("/DBRegister.xsd")) {
       whateverYouArePassingThatFileTo(in);
    }
    

    如果whateverYouArePassingThatFileTo() 没有接受InputStream 的变体,请删除该库并找到更好的库。

    【讨论】:

    • 由于资源是 XSD,我怀疑他想将资源 URL 传递给 SchemaFactory.newSchema(URL),如:SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI).newSchema(MigrationsApplication.class.getResource ("/DBRegister.xsd"))
    猜你喜欢
    • 2012-11-13
    • 2019-08-23
    • 2013-06-01
    • 2015-07-24
    • 2017-03-16
    • 2018-12-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多