Search code examples
javaimagepathrelative-path

Image from relative package


I'm making a simple game using the java applet. I want to add buffered images to the project.

I've created a package called "resources.images.sprites" and I've put images in there.

How can I access the images?

I've tried using relative paths, but "." starts outside of the bin, so if I were to put the game on a website, I wouldn't be able to access it.

Any ideas?

Here's the main code I'm using for testing...

package resources;

import java.io.File;
import java.util.HashMap;

import entities.Sprite;

public class ImageLibrary {

    private static final File sprite_path = new File(".");
    private static File[] sprite_files = sprite_path.listFiles();

    //private static HashMap<String,Sprite> sprite_map = new HashMap<String,Sprite>();

    public static void main(String[] args){
        System.out.println(sprite_files[0]); // To check the folder it's in...
    }

}

Edit: I took the accept answer, and then realized I could use the getPath method on the URL object to get what I wanted to achieve.


Solution

  • Use a ClassLoader.

    Classloader cl = ImageLibrary.class.getClassLoader();
    URL imageUrl = cl.getResource("resources/images/sprites/MyImage.png");
    

    Once you have a URL for the image you can turn that in to an InputStream if you need to.

    InputStream imageStream = imageUrl.openStream();