使用getClass()加载资源.getResource() [英] Loading resources using getClass().getResource()
问题描述
我正在尝试加载图像以在我的应用程序中用作图标。根据教程的适当方法是:
I am trying to load an image to use as an icon in my application. The appropriate method according to this tutorial is:
protected ImageIcon createImageIcon(String path, String description)
{
java.net.URL imgURL = getClass().getResource(path);
if (imgURL != null) {
return new ImageIcon(imgURL, description);
} else {
System.err.println("Couldn't find file: " + path);
return null;
}
}
所以,我放置了文件的位置,将它作为参数传递给此函数。这不起作用,即imgURL为空。当我尝试通过显式传递路径来创建ImageIcon时:
So, I placed the location of the file, and passed it as a parameter to this function. This didn't work, i.e. imgURL was null. When I tried creating the ImageIcon by passing in the path explicitly:
ImageIcon icon = new ImageIcon(path,"My Icon Image");
效果很好!因此,应用程序可以从显式定义的路径中获取图像,但是没有使用getResources()获取图像。在这两种情况下,路径变量的值都是相同的。为什么它不起作用?如何通过类加载器找到资源?
It worked great! So the application can pick up the image from an explicitly defined path, but didn't pick up the image using getResources(). In both cases, the value of the path variable is the same. Why wouldn't it work? How are resources found by the class loader?
谢谢。
推荐答案
您可以使用以下格式请求路径:
You can request a path in this format:
/package/path/to/the/resource.ext
甚至用于在内存中创建类的字节也是这样的:
Even the bytes for creating the classes in memory are found this way:
my.Class -> /my/Class.class
和 getResource
会给你一个URL,可以用来检索 InputStream
。
and getResource
will give you a URL which can be used to retrieve an InputStream
.
但是...我推荐使用相同的参数直接使用 getClass()。getResourceAsStream(...)
,因为它直接返回InputStream而不必担心创建(可能是复杂的)必须知道如何创建InputStream的URL对象。
But... I'd recommend using directly getClass().getResourceAsStream(...)
with the same argument, because it returns directly the InputStream and don't have to worry about creating a (probably complex) URL object that has to know how to create the InputStream.
简而言之:尝试使用 getResourceAsStream
和一些构造函数 ImageIcon
使用 InputStream
作为参数。
In short: try using getResourceAsStream
and some constructor of ImageIcon
that uses an InputStream
as an argument.
类加载器
如果您的应用有很多类加载器,请务必小心。如果你有一个简单的独立应用程序(没有服务器或复杂的东西),你不必担心。如果 ImageIcon
能够找到它,我不认为是这种情况。
Be careful if your app has many classloaders. If you have a simple standalone application (no servers or complex things) you shouldn't worry. I don't think it's the case provided ImageIcon
was capable of finding it.
编辑:classpath
getResource
is-as mattb说 - 用于从类路径加载资源(来自.jar)或类路径目录)。如果您正在捆绑一个应用程序,那么完全可以,所以您可以将图标文件包含在应用程序的jar中并以此方式获取。
getResource
is—as mattb says—for loading resources from the classpath (from your .jar or classpath directory). If you are bundling an app it's nice to have altogether, so you could include the icon file inside the jar of your app and obtain it this way.
这篇关于使用getClass()加载资源.getResource()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!