Yes you can do this.
Non-code resources in a JAR file on the classpath can be access 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, just copy it into the appropriate place in the input directory tree before you run the jar
command.
FOLLOW UP
In theory, your application could store files inside its own JAR file, under certain circumstances:
- The JAR has to be a file in the local file system; i.e. not a JAR that was fetched from a remote server.
- The application has to have write access to the JAR file and its parent directory.
- The application must not need to read back the file it wrote to the JAR in the current classloader; i.e. without exiting and restarting.
- The JAR must not need to be be signed.
The procedure would be:
- Locate the JAR file and open as a ZIP archive reader.
- Create a ZIP archive writer to write a new version of JAR file.
- Write the application's files to the writer.
- Write all resources from the ZIP reader to the writer, excluding old versions of the applications files.
- Close the reader and writer.
- 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 and more robust to just write regular files.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…