Unpacking a required resource library in a stand-alone JAR-file at Runtime
[with full credit and much gratitude to Steve Worsley (CS477, F07), who figured out this neat little solution and provided this brief tutorial]

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:
*Make sure that this folder coincides with the class-path in your runnable JAR's manifest file. In the case of netbeans library, you will want to use "lib" as your folder.
**In order to not crash on start-up, we need to unpack before we run the main class.

First, we need to create the desired library folder in the JAR's environment. This is done using the File class' mkdir() command. For example, lets make a "lib" directory:
  new File("lib").mkdir();
The code above will create the folder "lib" in whatever directory the JAR is being run from.

Second, we need to get a handle on the resource in our JAR file in stream format. This can be done simply with the getClass().getResourceAsStream() method, as illustrated below:
  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.

Third, we need to take this InputStream and write it to an actual file. This can be done with a simple method that utilizes a FileOutputStream to write the file to disk. This method, setFile, and an example usage are shown below:
  /**
   *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.