Jungleford's Home BlogJava分舵

Java技术研究,兼探讨历史话题

BlogJava 首页 新随笔 联系 聚合 管理
  24 Posts :: 0 Stories :: 53 Comments :: 0 Trackbacks

jungleford如是说

    可能有不少初学者会有这样的困惑(以前我也有过):在你的代码里调用了一些资源文件,如图片,音乐等,在调试环境或单独运行的时候可以正常显示或播放,而一旦打包到jar文件中,这些东东就再也出不来了,除非把这个jar放到原来未打包以前的目录下,但通常jar是单独发布的。这里介绍一个解决这类问题的方法。

getResource和getResourceAsStream

    问题的根源还是在于老生常谈的所谓class path,不信的话你在系统环境变量里的ClassPath加上你的jar文件,这下你就看得到你的图片了!但单独发布jar的话不可能指望每次都让用户为你的jar而专门修改classpath。那么有没有什么办法一劳永逸地搞定它呢?我们需要从类的装载入手。先扯远一点,在开发JSP之类的Web应用程序的时候要用到第三方的库怎么办?通常的做法是把这些库(可以是class,也可以是jar)统统放到WEB-INF/lib/目录下面,为什么这样系统就认了呢?因为Web容器(譬如Tomcat)在装载类的时候有自己的组织方式(可以参考Tomcat手册)。特别地,jar也是类装载器的一个可访问媒介,ClassLoader提供了两个方法用于从装载的类路径中取得资源:

public URL getResource(String name);
public InputStream getResourceAsStream(String name);


这里name是资源的类路径,它是相对与“/”根路径下的位置。getResource得到的是一个URL对象来定位资源,而getResourceAsStream取得该资源输入流的引用保证程序可以从正确的位置抽取数据。
    真正使用的不是ClassLoader的这两个方法,而是Class的getResource和getResourceAsStream方法,因为Class对象可以从你的类得到(如YourClass.class或YourClass.getClass()),而ClassLoader则需要再调用一次YourClass.getClassLoader()方法,但根据JDK文档的说法,Class对象的这两个方法其实是“委托”(delegate)给装载它的ClassLoader来做的,所以只需要使用Class对象的这两个方法就可以了。
    在参考资料中有一篇老外写的文章比较深入介绍了从jar中装载资源的方法。

一个应用的例子

    以下是在我写的一个小工具MSNHistoryCombiner中用到的一段代码,可以从jar中装载图片和文本信息。譬如,你的jar中根目录下有个img目录,里面放有一些图片,如img1.jpg,你可以这样调用

Utilities.getImageFromJar("/img/img1.jpg", YourClass.class);


注意必须这里是“/img/img1.jpg”而非“img/img1.jpg”。从jar中读文本资源也是类似方法调用getTextFromJar。
    需要说明的是,这段代码也不是我原创的,是从一段别的代码中经过修改得到的,但原代码的来源忘记了,在这里向原作者表示感谢和歉意。

import java.io.*;
import java.awt.
*;

public class Utilities
{
  
/**
   * <p>
   * Description: Return an Image based on the supplied image identifier. The
   * image is assumed to reside at the defined location within the same
   * repository as this class.
   
*/

  
public static Image getImageFromJar(final String imageId, Class c)
  
{
    
// Image reference initialised to null (the image may not be found).
    Image image = null;
    
// Open a resource stream on the supplied image identifier.
    final InputStream inputStream = c.getResourceAsStream(imageId);
    
// If the image data is found
    if (inputStream != null)
    
{
      
// Open a byte array output stream so that we can create a byte
      
// array with which to create the image.
      final ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
      
// Attempt to copy the source image data into the byte array
      
// stream, and then create an image from the result.
      try
      
{
        
// Read/write image data in 1k chunks.
        final byte[] bytes = new byte[1024];
        
int read = 0;
        
while ((read = inputStream.read(bytes)) >= 0)
        
{
          byteArrayOutputStream.write(bytes, 
0, read);
        }


        
// Create an image from the resulting byte array.
        image = Toolkit.getDefaultToolkit().createImage(
            byteArrayOutputStream.toByteArray());
      }

      
catch (IOException exception)
      
{
        exception.printStackTrace();
      }

    }

    
return image;
  }


  
public static String getTextFromJar(final String filename, Class c)
  
{
    String text 
= "";
    
// Open a resource stream on the supplied file name.
    final InputStream inputStream = c.getResourceAsStream(filename);
    
// If the file is found
    if (inputStream != null)
    
{
      final BufferedReader 
in = new BufferedReader(new InputStreamReader(
          inputStream));
      
try
      
{
        String s;
        
while ((s = in.readLine()) != null)
        
{
          text 
+= s + "\n";
        }

      }

      
catch (IOException exception)
      
{
        exception.printStackTrace();
      }

    }

    
return text;
  }

}


参考资料

J2SE API Documentation

用 One-JAR 简化应用程序交付

posted on 2005-06-11 12:41 jungleford 阅读(2955) 评论(2)  编辑  收藏 所属分类: 咖啡屋 - Java 技术研究

Feedback

# re: 从Jar包获取资源的方法 2006-02-28 09:52 skyswan
如果不知道具体的资源文件名,想列出所有的资源,怎么做呢?  回复  更多评论
  

# re: 从Jar包获取资源的方法 2006-03-11 19:09 jungleford
@skyswan
我没有具体作过,但我想作为jar包,java.util.jar中的工具应该可以找到所有资源吧  回复  更多评论
  


只有注册用户登录后才能发表评论。


网站导航: