2016-11-09 66 views
-1

這是我的代碼,我正在尋找一種將文件添加到正在運行的jar的方法。提前致謝。目前出現的錯誤是「無效的條目大小(預期的62,但得到0字節),62字節是我的MANIFEST文件的大小,它被寫入,我不確定什麼與任何事情有關。如何將文件添加到運行jar

 JarFile replace = new JarFile("newgame.jar"); 
     JarInputStream jis = null; 
     JarOutputStream jos = new JarOutputStream(new FileOutputStream(
       Launcher.class.getProtectionDomain().getCodeSource().getLocation().getPath())); 
     for (Enumeration<JarEntry> list = replace.entries(); list.hasMoreElements();) { 
      JarEntry nextEntry = list.nextElement(); 
      if (!nextEntry.getName().equals("Launcher.class")) { 
       jos.putNextEntry(nextEntry); 
       jis = new JarInputStream(replace.getInputStream(nextEntry)); 
       ByteArrayOutputStream out = new ByteArrayOutputStream(); 
       byte[] byteBuff = new byte[1024]; 
       int bytesRead = 0; 
       while ((bytesRead = jis.read(byteBuff)) != -1) 
        out.write(byteBuff, 0, bytesRead); 
       jos.write(out.toByteArray()); 
       out.close(); 
       jis.close(); 
      } 
     } 
     replace.close(); 
     jos.close(); 
     new File("newgame.jar").delete(); 
+0

爲什麼你要做到這一點,這可能是一個[XY問題(HTTP:// xyproblem。 info)。你的代碼中哪個語句給你錯誤? –

+0

@JimGarrison the jos.pu tNextEntry(nextEntry);給我的錯誤。 – Toxxic

回答

0

修正了

 JarFile replace = new JarFile("newgame.jar"); 
     InputStream is = null; 
     JarOutputStream jos = new JarOutputStream(new FileOutputStream(
       Launcher.class.getProtectionDomain().getCodeSource().getLocation().getPath())); 
     for (Enumeration<JarEntry> list = replace.entries(); list.hasMoreElements();) { 
      JarEntry nextEntry = list.nextElement(); 
      jos.putNextEntry(nextEntry); 
      is = replace.getInputStream(nextEntry); 
      ByteArrayOutputStream out = new ByteArrayOutputStream(); 
      byte[] byteBuff = new byte[(int) nextEntry.getSize()]; 
      int bytesRead = 0; 
      while ((bytesRead = is.read(byteBuff, 0, byteBuff.length)) != -1) 
       out.write(byteBuff, 0, bytesRead); 
      jos.write(out.toByteArray()); 
      out.close(); 
      is.close(); 
     } 
     replace.close(); 
     jos.close(); 
     new File("newgame.jar").delete(); 

我轉換JarInputStreams到InputStreams出於某種原因,這個工作