简体   繁体   中英

Loading an image from the Resource Folder

The code I am using to load the image is:

 ImageIO.read(SpriteSheet.class.getResource(path));

The path being the path to the resource. But it would error with IllegalArgumentException . I wondered what might be causing and came to the conclusion that the resource should be added into the same path as the class.

Is it possible to load the image from another folder, like a res folder outside of the bin folder? (folder holding compiled classes)

EDIT: So i messed around with a few things, and came to a solution. But now I have another problem. Here is my code

    File sheet = new File(SpriteSheet.class.getProtectionDomain().getCodeSource().getLocation().getPath());
URI uri = sheet.toURI();
    BufferedImage image = ImageIO.read(uri.toURL());

When I try to run it, it gives me an IIOException: Can't read Input File This means that I can never actually get it work. I tried debugging by prining the URL to the console and this is the URL. C:\\Users\\Amma\\Abhijeet\\Eclipse%20Workspace1\\Test%20Game\\bin The %20 comes in the middle. Meaning that the file is and never can be acceesed. Is there anyway I can fix this?

Thanks.

Class.getResource will return null if the resource could not be found or the invoker doesn't have adequate privileges to get the resource. All variants of ImageIO.read will throw an IllegalArgumentException if they receive a null input.

Take a look at the documentation of the getResource to understand how an absolute resource name is constructed from the given resource named and what are the rules for searching resources.

You can read images from any location as long as you have permissions to do so, the ImageIO.read method accepts a File, URL or InputStream so you have many option to do it.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM