Subscribe

RSS Feed (xml)

Powered By

Skin Design:
Free Blogger Skins

Powered by Blogger

Monday, November 19, 2007

Packaging resources (eg images, data, ...) with your jar file

Q: How can you include resources (like images, sound, data, etc) so that your Java program doesn't need to use file paths, and so that you can package these resources in the jar file? And how do you access these resources from your program?

A: The Java class loader that loaded your program knows where the resources are. You can ask it to get other resources from the jar file. But first you have to build the jar file to include these resources. NetBeans does this automatically if you put a directory of your resources in the right place.

  1. Adding your resources to the project.
    1. Locate the src folder in your NetBeans project folder. This will have subfolder(s) in it that correspond to the package(s) in your program. The final package folder will have the source code (.java files) for your program.
    2. Create a subfolder in the folder containing the .java files. Name this folder something like "resources" or "images" or whatever might be appropriate for your data.
    3. Copy your data files into this folder. Keep a backup copy of the data -- if you put it in the wrong folder, NetBeans may delete it.
    4. Build (or Clean and Build) your project. This will compile the code and copy the resources folder into the build/classes/your-packages folder of the NetBeans project. It will also be added to the jar file.
  2. Reading resources from your Java program.

    The following example shows how to read one line from the text file initial-board.sdk which is located in the resources directory. The main program is called Sudoku.

    //... Reads one line of text from a file saved in jar file.
    final String RESOURCE_LOCATION = "resources/initial-board.sdk";

    InputStream instream = Sudoku.class.getResourceAsStream(RESOURCE_LOCATION);
    Scanner in = new Scanner(instream);
    String initial_board = in.nextLine();
    in.close();

    There are a few things to note about this code.

    1. There are a couple of ways to get a Class object - either from the .class field if you specify the name of a class (as above), or by calling getClass() on an object.
    2. A Class object has two methods for getting resources:
      1. getResourceAsStream(name) which returns an InputStream that can be used with Scanner or any other way of reading. This is used in the example above.
      2. getResource(name) which returns a URL. The URL is more general and can be used to get the InputStream. It can also be used directly in the IconImage(url) constructor, or various other ways to get images (getImage()) or sound (getAudioClip()).

No comments:

Post a Comment

Archives