Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

getClassLoader().getResource() returns null

Tags:

java

applet

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:\project\src 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?

like image 263
Ali Avatar asked Mar 09 '09 10:03

Ali


People also ask

What does class getResource do?

The getResource() method of java Class class is used to return the resources of the module in which this class exists. The value returned from this function exists in the form of the object of the URL class.

How does getResource work in Java?

The getResource method finds a resource with the specified name. It returns a URL to the resource or null if it does not find the resource. Calling java. net.

Should we close getResourceAsStream?

You should always close streams (and any other Closeable, actually), no matter how they were given to you. Note that since Java 7, the preferred method to handle closing any resource is definitely the try-with-resources construct.

How do you send paths in getResourceAsStream?

getResourceAsStream , send the absolute path from package root, but omitting the first / . If you use Class. getResourceAsStream , send either a path relative the the current Class object (and the method will take the package into account), or send the absolute path from package root, starting with a / .


1 Answers

You don't need the slash at the start when getting a resource from a ClassLoader, because there's no idea of a "relative" part to start with. You only need it when you're getting a resource from a Class where relative paths go from the class's package level.

In addition, you don't want Test.class.getClass() as that gets the class of Test.class, which will be Class<Class>.

In other words, try either of these lines:

URL viaClass=Test.class.getResource("/assets/pacman.png");
URL viaLoader=Test.class.getClassLoader().getResource("assets/pacman.png");
like image 78
Jon Skeet Avatar answered Nov 02 '22 19:11

Jon Skeet