Skip to content
Advertisement

getClassLoader().getResource() returns null

I have this test app:

import java.applet.*;
import java.awt.*;
import java.net.URL;
public class Test extends Applet
{

    public void init()
    {
        URL some=Test.class.getClass().getClassLoader().getResource("/assets/pacman.png");
        System.out.println(some.toString());
        System.out.println(some.getFile());
        System.out.println(some.getPath());

    }
}

When I run it from Eclipse, I get the error:

java.lang.NullPointerException
    at Test.init(Test.java:9)
    at sun.applet.AppletPanel.run(Unknown Source)
    at java.lang.Thread.run(Unknown Source)

Classpath (from .CLASSPATH file)

<classpathentry kind="src" path="src"/>

In my c:projectsrc folder, I have only the Test.java file and the ‘assets’ directory which contains pacman.png.

What am I doing wrong and how to resolve it?

Advertisement

Answer

I would do it this way:

final InputStream stream;

stream = Test.class.getResourceAsStream("assets/pacman.png");
System.out.println("Stream = " + stream);

“/assets/pacman.png” is an absolute location whle “assets/pacman.png” is a relative location.

Advertisement