Oftentimes we will work on a Java project where certain resources (e.g. images, sounds, movie clips) will be required by our program at runtime. Typically, we can just have a library folder outside of our runnable jar, referenced by the class-path, which will contain our resources. This can be a major problem, however, when we want to have a standalone java application run with just the executable JAR file. There are several complicated solutions out there for single JAR packaging, but for a quick, easy, and pain-free solution we can have our program automatically "unpack" its own library folder! This tutorial is created to help you do just that.
Here is a general overview of what we need to do to achieve our goal: new File("lib").mkdir();
The code above will create the folder "lib" in whatever directory the JAR is being run from.
InputStream input = getClass().getResourceAsStream("/lib/swing-layout-1.0.jar");
This code will get an InputStream from the given resource. In this case, the file "swing-layout-1.0.jar" is located in the "lib" folder of our runnable JAR. /**
*Writes a file given the inputstream and filename.
*Used for unpacking the JAR.
*
*@param io Source InputStream to be written to a file
*@param fileName Name of file to be written
*/
public void setFile(InputStream io, String fileName)
throws IOException {
FileOutputStream fos = new FileOutputStream(fileName);
byte[] buf = new byte[256];
int read = 0;
while ((read = io.read(buf)) > 0) {
fos.write(buf, 0, read);
}
}
setFile(getClass().getResourceAsStream("/lib/swing-layout-1.0.jar"),"lib/swing-layout-1.0.jar");
Lastly, start the main application. Now that the libraries are in place, the program should be up and running!
A piece of sample code that shows how all of this comes together can be seen here: LibUnpacker.java.