服务热线:13616026886

技术文档 欢迎使用技术文档,我们为你提供从新手到专业开发者的所有资源,你也可以通过它日益精进

位置:首页 > 技术文档 > JAVA > 新手入门 > 基础入门 > 查看文档

如何在applet中引用jar中的资源文件


如果想要做一个比较漂亮的applet让人家使用,一定会加上很多资源,比如图片或者声音文件什么的。

sun提供了一个有用的工具,jar。这个工具可以把这些资源文件合在一个文件里,避免频繁的http request,
而且下载的jar文件可以被缓存,很爽吧。

但是如何正确引用jar中的资源呢?

比如我们打算显示一个图片按钮,图片相对路径为./img/logo.gif,你可以自己随便找一个gif图片。

让我们来看看我们想当然的做法。


import java.awt.*;
import java.awt.event.*;

import javax.swing.*;

public class imagebuttonapplet extends japplet
{
private string path = "/img/logo.gif";
private imageicon logobuttonicon = new imageicon(path);

/**initialize the applet*/
public void init()
{
try
{
if (logobuttonicon == null)
throw new exception("cannot get the image!");

jbutton ibutton = new jbutton(logobuttonicon);

container cp = this.getcontentpane();
cp.add(ibutton);
}
catch (exception e)
{
e.printstacktrace();
}
}
}

这样子编译之后,把imagebuttonapplet.class和logo.gif保持相对路径打进jar里面,对应的html页面代码为<applet code = "imagebuttonapplet.class" codebase = "." archive = "test.jar" width = "200" height = "200"></applet>,由于使用了swing,
经过htmlconverter预处理之后,本以为能够一举成功,打开页面却发现,抛出异常:
java.security.accesscontrolexception: access denied (java.io.filepermission /img/logo.gif read)

这件事情也郁闷了我很久,反复试验,不管path相对路径还是什么,都不能顺利实现。

后来我研究了jdk自带的demo,发现demo在引用资源的时候,采用这样的方法 getclass().getresource(string sourcename);

getclass()是object的方法,返回一个对象的运行时类型,即class对象。

原来class对象有getresource方法,在api文档中就是这样写的:

public url getresource(string name)

finds a resource with a given name. this method returns null if no resource with this name is found. the rules for searching resources associated with a given class are implemented by the * defining class loader of the class.

this method delegates the call to its class loader, after making these changes to the resource name: if the resource name starts with "/", it is unchanged; otherwise, the package name is prepended to the resource name after converting "." to "/". if this object was loaded by the bootstrap loader, the call is delegated to classloader.getsystemresource.

parameters:
name - name of the desired resource

returns:
a java.net.url object.

since:
jdk1.1

see also:
classloader

如法炮制,我把原来的

private imageicon logobuttonicon = new imageicon(path);

改成

private imageicon logobuttonicon = new imageicon(getclass().getresource(path));

编译,jar,run,成功,无论是本机打开还是放到http服务器中,都没有问题了。

这就是在applet中引用jar中资源文件的key!

扫描关注微信公众号