Question

I'm trying to get a resource (image.png, in the same package as this code) from a static method using this code:

import java.net.*;

public class StaticResource {

    public static void main(String[] args) {
        URL u = StaticResource.class.getClass().getResource("image.png");
        System.out.println(u);
    }

}

The output is just 'null'

I've also tried StaticResource.class.getClass().getClassLoader().getResource("image.png"); , it throws a NullPointerException

I've seen other solutions where this works, what am I doing wrong?

Was it helpful?

Solution

Remove the ".getClass()" part. Just use

URL u = StaticResource.class.getResource("image.png");

OTHER TIPS

Always try to place the resources outside the JAVA code to make it more manageable and reusable by other package's class.

You can try any one

// Read from same package 
URL url = StaticResource.class.getResource("c.png");

// Read from same package 
InputStream in = StaticResource.class.getResourceAsStream("c.png");

// Read from absolute path
File file = new File("E:/SOFTWARE/TrainPIS/res/drawable/c.png");

// Read from images folder parallel to src in your project
File file = new File("images/c.jpg");

// Read from src/images folder
URL url = StaticResource.class.getResource("/images/c.png")

// Read from src/images folder
InputStream in = StaticResource.class.getResourceAsStream("/images/c.png")
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top