<rt id="bn8ez"></rt>
<label id="bn8ez"></label>

  • <span id="bn8ez"></span>

    <label id="bn8ez"><meter id="bn8ez"></meter></label>

    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 閱讀(2975) 評論(2)  編輯  收藏 所屬分類: 咖啡屋 - Java 技術研究

    Feedback

    # re: 從Jar包獲取資源的方法 2006-02-28 09:52 skyswan
    如果不知道具體的資源文件名,想列出所有的資源,怎么做呢?  回復  更多評論
      

    # re: 從Jar包獲取資源的方法 2006-03-11 19:09 jungleford
    @skyswan
    我沒有具體作過,但我想作為jar包,java.util.jar中的工具應該可以找到所有資源吧  回復  更多評論
      

    主站蜘蛛池模板: 成人黄页网站免费观看大全| 毛片无码免费无码播放| 久久久久免费看黄A片APP| 亚洲欧洲综合在线| 色片在线免费观看| 亚洲国产综合自在线另类| 成人免费黄色网址| 亚洲首页国产精品丝袜| 成年男女男精品免费视频网站| 亚洲中文字幕AV在天堂| 永久免费观看的毛片的网站| 国产亚洲精品91| 久久精品国产精品亚洲人人| a级日本高清免费看| 亚洲AV日韩AV天堂久久 | 亚洲精彩视频在线观看| 无码人妻久久一区二区三区免费| 久久精品国产亚洲av麻豆色欲| 222www免费视频| 亚洲熟女综合色一区二区三区| 国产精品四虎在线观看免费| 午夜在线免费视频| 亚洲精品卡2卡3卡4卡5卡区| 久久精品毛片免费观看| 亚洲色www永久网站| 亚洲福利精品电影在线观看| 少妇性饥渴无码A区免费| 亚洲中文字幕在线无码一区二区 | 免费无码午夜福利片| 亚洲乱码精品久久久久..| 在线观看免费中文视频| 亚洲GV天堂GV无码男同| 国产成人精品日本亚洲专区61| 日韩午夜理论免费TV影院| 亚洲日韩亚洲另类激情文学| 亚洲一区日韩高清中文字幕亚洲| 午夜无码A级毛片免费视频| 亚洲熟伦熟女专区hd高清| 在线亚洲精品自拍| 手机在线看永久av片免费| 中文字幕免费观看全部电影|