简体   繁体   English

从与应用程序相同的JAR文件中引用文件

[英]Referencing file from within the same JAR file as the application

I have a Java application in Eclipse that references .XML files as templates for other functionality. 我在Eclipse中有一个Java应用程序,该应用程序将.XML文件引用为其他功能的模板。 Usually I package the .JAR file without these files, because placing them within the same folder as the .JAR file seems to work fine with this reference: 通常,我打包不带这些文件的.JAR文件,因为将它们放置在与.JAR文件相同的文件夹中,使用此引用似乎可以正常工作:

File myFile = new File("templates/templateA.xsd");

I now require that these templates be placed within the same .JAR file as this application. 现在,我要求将这些模板放置在与此应用程序相同的.JAR文件中。 I can include them with no problems, but these references no longer seem to work. 我可以毫无问题地包含它们,但是这些参考似乎不再起作用。

Is there a correct way of referencing the .XML file from within the same .JAR that the application is running from? 是否有从应用程序运行所在的同一.JAR中引用.XML文件的正确方法?

You need to know how to load the files from class path. 您需要知道如何从类路径加载文件。 one of the ways is as follows 方式之一如下

class XMLLoader {

    public String loadXML(String fileName){
         InputStream inputStream = this.getClass().getClassLoader().getResourceAsStream(fileName);
    // do the loading of the file from the given input stream.
   }

} }

you know that the "templates" folder should be inside of your jar. 您知道“ templates”文件夹应该在jar中。

If you just need to read this file, you might not need a java.io.File but just an InputStream that you can get via 如果您只需要读取此文件,则可能不需要java.io.File,而只需输入即可通过

this.getClass().getResourceAsStream("templates/templateA.xsd")

If you really need a java.io.File... I do not know... The last time a really needed a File, I just copied the InputStream to a temporary file but this is ugly. 如果您确实需要java.io.File ...我不知道...上一次真正需要一个File时,我只是将InputStream复制到一个临时文件,但这很丑陋。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM