javajararchive

How can my Java program store files inside of its .jar file?


I know that .jar files are basically archives as well as being applications. What I'm asking is how can I store data(actual files not just strings) packed inside my program? I want to do this within my Java code.

The reason for this if your wondering is that I'm producing a server mod of a game. The server starts and creates all the level data and I want to store all these file inside my .jar app.


Solution

  • Yes you can do this.

    Non-code resources in a JAR file on the classpath can be accessed using Class.getResourceAsStream(String). Applications routinely do this, for example, to embed internationalized messages as resource bundles.

    To get your file into the JAR file (at project build time!), just copy it into the appropriate place in the input directory tree before you run the jar command. Build tools such as Maven, Gradle, etc can automate that for you.


    Is there a way to add files to the archive within the app?

    In theory, your application could store files inside its own JAR file, under certain circumstances:

    The procedure would be:

    1. Locate the JAR file and open as a ZIP archive reader.
    2. Create a ZIP archive writer to write a new version of JAR file.
    3. Write the application's files to the writer.
    4. Write all resources from the ZIP reader to the writer, excluding old versions of the applications files.
    5. Close the reader and writer.
    6. Rename the new version of the JAR to replace the old one.

    The last step might not work if the initial JAR is locked by the JVM / OS. In that case, you need do the renaming in a wrapper script.

    However, I think that most people would agree that this is a BAD IDEA. It is simpler, more robust and more secure to just write the stuff you want to save as regular files in the filesystem.