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?
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.
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.
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.
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 / .
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");
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With