繁体   English   中英

以编程方式将一个jar文件复制到另一个jar文件

[英]Programatically copy one jar file into another jar file

我想使用以下代码将jar文件复制到文件夹中

   public static void copyJarFile(JarFile jarFile, File destDir) throws IOException {
       String fileName = jarFile.getName();
       String fileNameLastPart = fileName.substring(fileName.lastIndexOf(File.separator));
       File destFile = new File(destDir, fileNameLastPart);

       JarOutputStream jos = new JarOutputStream(new FileOutputStream(destFile));
       Enumeration<JarEntry> entries = jarFile.entries();

       while (entries.hasMoreElements()) {
           JarEntry entry = entries.nextElement();
           InputStream is = jarFile.getInputStream(entry);

           //jos.putNextEntry(entry);
           //create a new entry to avoid ZipException: invalid entry compressed size
           jos.putNextEntry(new JarEntry(entry.getName()));
           byte[] buffer = new byte[4096];
           int bytesRead = 0;
           while ((bytesRead = is.read(buffer)) != -1) {
               jos.write(buffer, 0, bytesRead);
           }
           is.close();
           jos.flush();
           jos.closeEntry();
       }
       jos.close();
   }

该程序运行良好。 但是,如果目标位置不是目录而是jar文件,则此程序将无法运行。 即我想将一个jar文件复制到另一个jar文件中。 如何以编程方式做到这一点?

Jar文件只是具有特定文件结构和扩展名.jar的精美zip文件。 所以,如果你能够用这个东西都堆到一个文件夹,该文件夹中有你要找的确切结构,你可以拉上该目录为一个zip文件,然后重命名zip文件whatever.jar代替whatever.zip

当您说I want to copy one jar file into another jar file ,您的意思到底是什么?

假设您原始的原始jar名为a.jar ,并且您想创建b.jar 您是否要像原来一样将a.jar所有项目都放在b.jar中? 还是你想b.jar包含称为入口a.jar即是一个完整的副本a.jar

如果您只是希望b.jara.jar所有项目都包含a.jar ,那么您当前的代码应该可以使用,尽管这样做的效率更高。 如果这是您的意思,我建议您直接复制文件。

如果要在b.jar添加整个a.jar作为条目,而不是循环浏览a.jar的条目,则只需从a.jar创建一个FileInputStream并从中读取。

InputStream is = new FileInputStream("a.jar");

jos.putNextEntry(new JarEntry("a.jar"));
byte[] buffer = new byte[4096];
int bytesRead;
while ((bytesRead = is.read(buffer)) != -1) {
    jos.write(buffer, 0, bytesRead);
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM