2010-02-09 72 views
1

如何以編程方式將所有資源文件加載到JAR文件中給定目錄中的applet?這些資源可能會在程序的整個生命週期中改變幾次,所以我不想硬編碼名稱。在Java applet中加載目錄中的所有文件

通常我只是使用File.list()來遍歷目錄結構,但在嘗試時遇到權限問題在一個小程序內完成。我還研究了使用具有ClassLoader.getResources()行的枚舉,但它僅在JAR文件中查找具有相同名稱的文件。

基本上我想要做的是(像)這樣的:

ClassLoader imagesURL = this.getClass().getClassLoader(); 
MediaTracker tracker = new MediaTracker(this); 
Enumeration<URL> images = imagesURL.getResources("resources/images/image*.gif"); 
while (images.hasMoreElements()){ 
    tracker.add(getImage(images.nextElement(), i); 
    i++; 
} 

我知道我可能錯過了一些明顯的作用,但我花了幾個小時,通過教程和文檔的簡單方式搜索在未簽名的小程序中執行此操作。

回答

1

你可以做到這一點有兩種方式:

  1. 重命名您的圖像,所以您可以通過一些算法,列舉出來(例如image_1image_2image_3),那麼你就可以收集你一氣呵成需要的所有資源。
  2. 否則你需要編碼很多。這個想法是,你必須:

    • 確定您的JAR文件的路徑:

      private static final String ANCHOR_NAME = "some resource you know"; 
      
      URL location = getClass().getClassLoader().getResource(ANCHOR_NAME); 
      URL jarLocation; 
      String protocol = location.getProtocol(); 
      if (protocol.equalsIgnoreCase("jar")) 
      { 
          String path = location.getPath(); 
          int index = path.lastIndexOf("!/" + ANCHOR_NAME); 
          if(index != -1) 
           jarLocation = new URL(path.substring(0, index)); 
      } 
      if (protocol.equalsIgnoreCase("file")) 
      { 
          String string = location.toString(); 
          int index = string.lastIndexOf(ANCHOR_NAME); 
          if(index != -1) 
           jarLocation = new URL(string.substring(0, index)); 
      } 
      
    • 打開它java.util.jar.JarFile

      JarFile jarFile = new JarFile(jarLocation); 
      
    • 迭代通過所有項目和符合他們的名稱與給定的面具

      for (Enumeration entries = jarFile.entries(); entries.hasMoreElements();) 
      { 
          JarEntry entry = (JarEntry) entries.nextElement(); 
          String entryPath = entry.getName(); 
          if (entryPath.endsWith(".jpg")) 
          { 
           // do something with it 
          } 
      } 
      

如需其他代碼支持,我會將您推薦到Spring PathMatchingResourcePatternResolver#doFindPathMatchingJarResources()