2012-06-16 50 views
0

注意:這是一個後續我的問題here.從外部JAR無法檢索資源文​​件


我有一個程序,將一個目錄的內容,一切都捆綁到一個JAR文件。我用它來做到這一點的代碼是在這裏:

try 
    { 
     FileOutputStream stream = new FileOutputStream(target); 
     JarOutputStream jOS = new JarOutputStream(stream); 

     LinkedList<File> fileList = new LinkedList<File>(); 
     buildList(directory, fileList); 

     JarEntry jarAdd; 

     String basePath = directory.getAbsolutePath(); 
     byte[] buffer = new byte[4096]; 
     for(File file : fileList) 
     { 
      String path = file.getPath().substring(basePath.length() + 1); 
      path.replaceAll("\\\\", "/"); 
      jarAdd = new JarEntry(path); 
      jarAdd.setTime(file.lastModified()); 
      jOS.putNextEntry(jarAdd); 

      FileInputStream in = new FileInputStream(file); 
      while(true) 
      { 
       int nRead = in.read(buffer, 0, buffer.length); 
       if(nRead <= 0) 
        break; 
       jOS.write(buffer, 0, nRead); 
      } 
      in.close(); 
     } 
     jOS.close(); 
     stream.close(); 

所以,一切都很好,好,罐子被創建,當我與探討其內容的7-Zip它有我需要的所有文件。但是,當我嘗試通過URLClassLoader訪問Jar的內容(該jar不在類路徑中,我不打算這樣做)時,我得到空指針異常。

奇怪的是,當我使用從Eclipse導出的Jar時,我可以以我想要的方式訪問它的內容。這使我相信我不知道如何正確創建Jar,並且正在拋出一些東西。上面的方法有什麼缺失嗎?

+1

您可能會發現[如何使用的JarOutputStream創建一個JAR文件(http://stackoverflow.com/q/1281229/1048330)是有用的。 – tenorsax

+0

您是否嘗試向jar添加清單文件? –

+0

@Max謝謝你,這正是我所需要的。問題是反斜槓;我沒有正確使用String.replaceAll。 – CodeBunny

回答

1

我想到了基於this question - 問題是我沒有正確處理反斜槓。

固定的代碼是在這裏:

 FileOutputStream stream = new FileOutputStream(target); 
     JarOutputStream jOS = new JarOutputStream(stream); 

     LinkedList<File> fileList = new LinkedList<File>(); 
     buildList(directory, fileList); 

     JarEntry entry; 

     String basePath = directory.getAbsolutePath(); 
     byte[] buffer = new byte[4096]; 
     for(File file : fileList) 
     { 
      String path = file.getPath().substring(basePath.length() + 1); 
      path = path.replace("\\", "/"); 
      entry = new JarEntry(path); 
      entry.setTime(file.lastModified()); 
      jOS.putNextEntry(entry); 
      FileInputStream in = new FileInputStream(file); 
      while(true) 
      { 
       int nRead = in.read(buffer, 0, buffer.length); 
       if(nRead <= 0) 
        break; 
       jOS.write(buffer, 0, nRead); 
      } 
      in.close(); 
      jOS.closeEntry(); 
     } 
     jOS.close(); 
     stream.close(); 
+0

您應該將此標記爲接受的答案。告訴其他人這個問題已經解決了。 –

+0

它說我需要等一天。 – CodeBunny