现在的位置: 首页 > 综合 > 正文

从JAR包中获取资源的方法

2013年10月21日 ⁄ 综合 ⁄ 共 3527字 ⁄ 字号 评论关闭

jungleford如是说

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

getResource和getResourceAsStream

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

  1.     public URL getResource(String name);
  2.     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,你可以这样调用

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

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

  1. import java.io.*;
  2. import java.awt.*;
  3. public class Utilities
  4. {
  5.   /**
  6.    * <p>
  7.    * Description: Return an Image based on the supplied image identifier. The
  8.    * image is assumed to reside at the defined location within the same
  9.    * repository as this class.
  10.    */
  11.   public static Image getImageFromJar(final String imageId, Class c)
  12.   {
  13.     // Image reference initialised to null (the image may not be found).
  14.     Image image = null;
  15.     // Open a resource stream on the supplied image identifier.
  16.     final InputStream inputStream = c.getResourceAsStream(imageId);
  17.     // If the image data is found...
  18.     if (inputStream != null)
  19.     {
  20.       // Open a byte array output stream so that we can create a byte
  21.       // array with which to create the image.
  22.       final ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
  23.       // Attempt to copy the source image data into the byte array
  24.       // stream, and then create an image from the result.
  25.       try
  26.       {
  27.         // Read/write image data in 1k chunks.
  28.         final byte[] bytes = new byte[1024];
  29.         int read = 0;
  30.         while ((read = inputStream.read(bytes)) >= 0)
  31.         {
  32.           byteArrayOutputStream.write(bytes, 0, read);
  33.         }
  34.         // Create an image from the resulting byte array.
  35.         image = Toolkit.getDefaultToolkit().createImage(
  36.             byteArrayOutputStream.toByteArray());
  37.       }
  38.       catch (IOException exception)
  39.       {
  40.         exception.printStackTrace();
  41.       }
  42.     }
  43.     return image;
  44.   }
  45.   public static String getTextFromJar(final String filename, Class c)
  46.   {
  47.     String text = "";
  48.     // Open a resource stream on the supplied file name.
  49.     final InputStream inputStream = c.getResourceAsStream(filename);
  50.     // If the file is found...
  51.     if (inputStream != null)
  52.     {
  53.       final BufferedReader in = new BufferedReader(new InputStreamReader(
  54.           inputStream));
  55.       try
  56.       {
  57.         String s;
  58.         while ((s = in.readLine()) != null)
  59.         {
  60.           text += s + "/n";
  61.         }
  62.       }
  63.       catch (IOException exception)
  64.       {
  65.         exception.printStackTrace();
  66.       }
  67.     }
  68.     return text;
  69.   }
  70. }

抱歉!评论已关闭.