Code Snippets

Have a useful piece of code you want to share with the class? Post it here!

Getting resources from a JAR file without using the getResource() method

I have some images bundled in a JAR file with the rest of the src and audio files for my game. I was able to access the images simply using

getImage(getCodeBase(), "images/image0.jpg");

where the JAR file contains a directory named 'images' which contains 'image0.jpg'

Reading in a text file (Applet)

I know at least a couple people were trying to load a plain text file for their applets. Here's how to load one from a JAR file in your applet. For this to work, you need to have the JAR file with the text file included in the "archives" parameter of your APPLET tag.

public boolean printTextFile(String filename) {
    InputStream input = getClass().getResourceAsStream(filename);
    BufferedReader reader = new BufferedReader(new InputStreamReader(input));
    String line;

    try {
        while ((line = reader.readLine()) != null) {
    } catch (IOException e) {
        return false;

    return true;

Usage: Assuming you have a file called "test.txt" in the root of a JAR file that has been included in your list of archives, you can print the text file using the following call:


Obviously, since you now have access to the file via an InputStream and/or BufferedReader, you can do basically anything you want to do with the file.

Playing an MP3 File (Applet)

Code to play an MP3 file in your applet:

import java.applet.Applet;
import javazoom.jl.player.*;
import javazoom.jl.decoder.JavaLayerException;

//inside an Applet somewhere...

public void playSample() {
    /* Load an InputStream from a JAR. This file is located in 
     * resources.jar!/test.mp3 */
    InputStream mp3Stream = getClass().getResourceAsStream("/test.mp3");

    try {
        /* The Player class takes an InputStream in its constructor */
        Player mp3Player = new Player(mp3Stream);
        /* The MP3 InputStream has been loaded from the JAR, so now 
         * we can play the MP3 */;	
    } catch (JavaLayerException e) {

Details: This code assumes you have a file called "test.mp3" in a JAR file that has been included in your list of archives in your HTML page. For example, in my tests I put "test.mp3" in "resources.jar". My main Applet class is in "Shatter.jar" at path "Shatter/MP3Player.class". This is the code I needed to use in my HTML page:

<APPLET archive="resources.jar, Shatter.jar, lib/jl1.0.jar" code="Shatter/MP3Player.class" width=350 height=200></APPLET>

There is a demo available at:

Side Note: You should be able to load any type of resource into an InputStream and then manipulate the stream to get the data. For example, reading a text file like Jeff was trying to do.

loadImageURL: static, blocking version of Applet.getImage.


 * Loads an image from a given URL, timing out after a specified time. This method 
 * blocks until the image is loaded.
 * @param path The URL of the image you want to load.
 * @param timeout Number of seconds to wait before timing out. Setting this parameter to zero 
 * will load the image without a timeout.
 * @return An Image object with the completely loaded image on success, or null if an 
 * error has occured.
public static Image loadImageURL(String path, long timeout) {
    URL url;
    Toolkit toolkit = Toolkit.getDefaultToolkit();
    /* make a media tracker for a new container (so we can be static) */
    MediaTracker mediaTracker = new MediaTracker(new Container());

    /* convert path to a URL object */
    try {
        url = new URL(path);
    } catch (MalformedURLException e) {
        /* error with url format */
        return null;

    /* start downloading the image */
    Image image = toolkit.getImage(url);
    /* track the image status using the media tracker */
    mediaTracker.addImage(image, 0);

    /* wait for the image to load */
    try {
        if (timeout == 0) {
            /* wait with no timeout */
        } else {
            /* wait with timeout */
            mediaTracker.waitForID(0, timeout * 1000);
    } catch (InterruptedException e) {
        /* error */
        return null;

    /* error loading the image */
    if (mediaTracker.isErrorID(0)) {
        return null;

    /* return the image */
    return image;

Example Usage:

public void paint(Graphics g) {
    /* Little status message */
    g.drawString("Loading image. Please wait...", 20, 20);

    /* try to load this image with a 10 second timeout */
    Image image = loadImageURL("", 10);

    if (image != null) {
        /* draw the image if it was download properly */
        g.drawImage(image, 0, 0, 1024, 768, this);
    } else {
        /* else signal an error */
        g.drawString("Error downloading image", 20, 20);