Search code examples
javareferencejarinternal

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?


Solution

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