问题
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?
回答1:
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.
回答2:
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");
回答3:
Click Upvote,
- When you use
.getClass().getResource(fileName)
it considers the location of the fileName is the same location of the of the calling class. - When you use
.getClass().getClassLoader().getResource(fileName)
it considers the location of the fileName is the root - in other words bin folder
It hits NullPointerException
if the file is actually not exist there.
Source:
package Sound;
public class ResourceTest {
public static void main(String[] args) {
String fileName = "Kalimba.mp3";
System.out.println(fileName);
System.out.println(new ResourceTest().getClass().getResource(fileName));
System.out.println(new ResourceTest().getClass().getClassLoader().getResource(fileName));
OutPut ;
Kalimba.mp3
file:/C:/Users/User/Workspaces/MyEclipse%208.5/JMplayer/bin/Sound/Kalimba.mp3
file:/C:/Users/User/Workspaces/MyEclipse%208.5/JMplayer/bin/Kalimba.mp3
}
}
回答4:
This works for me:
URL viaClass=Test.class.getResource("assets/test.html");
which assets in the same folder with Test.class output file (after a miserable checking and debugging)
来源:https://stackoverflow.com/questions/625687/getclassloader-getresource-returns-null