简体   繁体   中英

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. 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:

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

I now require that these templates be placed within the same .JAR file as this application. 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?

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.

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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