javaimageresourcesurlclassloader

UrlClassLoader to load a image resource


I am creating an eclipse workspace starting by a java project (not written by me). I am facing problems with the following method:

    public static URL getURL(String fileName) {
       URLClassLoader urlLoader = (URLClassLoader) getInstance().getClass()
            .getClassLoader();

       URL fileLocation = urlLoader.findResource(fileName);

       return fileLocation;

since the findResource doesn't find the JPG resource (filename = "icons/INIT.JPG").

Looking on urlLoader.getUrl, I noticed the class aims only to jar files. Adding the folder icon to the Project->Libraries under eclipse I managed to let findResources look into the icon folder: nevertheless, the image is not a jar file and so it isn't considered.

Honestly, I don't get the point of using this process to load an image, but I cannot change the code and I was hoping in a solution within Eclipse project setup.

Thanks in advance


Solution

  • Based on the answers to my questions in the original comment, there are some facts:

    You said that the project is guaranteed to work without to move the file anywhere, so there's only one option: add the file that you want to retrieve with the ClassLoader to the classpath.

    1. Right click on the project, select Build Path and choose Configure Build Path.
    2. Click on Source > Add Folder... and add the folder where the resources that you want to take are.

    PD: If you add the folder as Class Folder in the Libraries tab, the JPG image won't be recognised by the AppClassLoader.