getClassLoader()。getResource()返回null [英] getClassLoader().getResource() returns null
本文介绍了getClassLoader()。getResource()返回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());
}
}
当我从Eclipse运行时,我收到错误:
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(来自.CLASSPATH文件)
Classpath (from .CLASSPATH file)
<classpathentry kind="src" path="src"/>
在我的c:\ project \ src文件夹中,我只有Test.java文件和'assets'目录,其中包含pacman.png。
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?
推荐答案
我会这样做:
final InputStream stream;
stream = Test.class.getResourceAsStream("assets/pacman.png");
System.out.println("Stream = " + stream);
/ assets / pacman.png是绝对的位置,assets / pacman.png是相对位置。
"/assets/pacman.png" is an absolute location whle "assets/pacman.png" is a relative location.
这篇关于getClassLoader()。getResource()返回null的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文