Java:在运行时将类添加到 Jar 存档中

2023-12-12

我想在运行时将一些编译的类(.class 文件)添加到当前 Jar 文件中的目录(包)
我怎样才能做到这一点?

Thanks


这是无法完成的 - 要更新 Jar 文件,您需要创建一个新文件并用新文件覆盖旧文件。

以下是有关如何执行此操作的示例:

import java.io.*;
import java.util.*;
import java.util.zip.*;
import java.util.jar.*;

public class JarUpdate {
   /**
    * main()
    */
   public static void main(String[] args) throws IOException {
      // Get the jar name and entry name from the command-line.

      String jarName = args[0];
      String fileName = args[1];

      // Create file descriptors for the jar and a temp jar.

      File jarFile = new File(jarName);
      File tempJarFile = new File(jarName + ".tmp");

      // Open the jar file.

      JarFile jar = new JarFile(jarFile);
      System.out.println(jarName + " opened.");

      // Initialize a flag that will indicate that the jar was updated.

      boolean jarUpdated = false;

      try {
         // Create a temp jar file with no manifest. (The manifest will
         // be copied when the entries are copied.)

         Manifest jarManifest = jar.getManifest();
         JarOutputStream tempJar =
            new JarOutputStream(new FileOutputStream(tempJarFile));

         // Allocate a buffer for reading entry data.

         byte[] buffer = new byte[1024];
         int bytesRead;

         try {
            // Open the given file.

            FileInputStream file = new FileInputStream(fileName);

            try {
               // Create a jar entry and add it to the temp jar.

               JarEntry entry = new JarEntry(fileName);
               tempJar.putNextEntry(entry);

               // Read the file and write it to the jar.

               while ((bytesRead = file.read(buffer)) != -1) {
                  tempJar.write(buffer, 0, bytesRead);
               }

               System.out.println(entry.getName() + " added.");
            }
            finally {
               file.close();
            }

            // Loop through the jar entries and add them to the temp jar,
            // skipping the entry that was added to the temp jar already.

            for (Enumeration entries = jar.entries(); entries.hasMoreElements(); ) {
               // Get the next entry.

               JarEntry entry = (JarEntry) entries.nextElement();

               // If the entry has not been added already, add it.

               if (! entry.getName().equals(fileName)) {
                  // Get an input stream for the entry.

                  InputStream entryStream = jar.getInputStream(entry);

                  // Read the entry and write it to the temp jar.

                  tempJar.putNextEntry(entry);

                  while ((bytesRead = entryStream.read(buffer)) != -1) {
                     tempJar.write(buffer, 0, bytesRead);
                  }
               }
            }

            jarUpdated = true;
         }
         catch (Exception ex) {
            System.out.println(ex);

            // Add a stub entry here, so that the jar will close without an
            // exception.

            tempJar.putNextEntry(new JarEntry("stub"));
         }
         finally {
            tempJar.close();
         }
      }
      finally {
         jar.close();
         System.out.println(jarName + " closed.");

         // If the jar was not updated, delete the temp jar file.

         if (! jarUpdated) {
            tempJarFile.delete();
         }
      }

      // If the jar was updated, delete the original jar file and rename the
      // temp jar file to the original name.

      if (jarUpdated) {
         jarFile.delete();
         tempJarFile.renameTo(jarFile);
         System.out.println(jarName + " updated.");
      }
   }
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

Java:在运行时将类添加到 Jar 存档中 的相关文章

随机推荐

  • 适用于 Android 的 libjpeg-turbo

    I need libjpeg turbo对于安卓NDK 有人设法将其编译为 a 静态 lib 吗 我已经尝试了几次 但它只给了我很多错误 安装Android NDK 以下说明经过验证r8b 老版本可能有问题 我不知道 获取 Android
  • 如何在linux上运行aout?

    问题是如何在 Linux 系统上执行 aout format 二进制文件 我的意思是旧格式 例如在迁移到 ELF 之前在 FreeBSD 上使用的格式 是否有可能在没有额外编码的情况下做到这一点 是否有一些现有的解决方案 也许它应该是 Li
  • Laravel 8 - 外键约束的形成不正确

    我不知道出了什么问题 因为我对此很陌生 Product Model class Product extends Model use HasFactory public function store return this gt belong
  • Heroku —“很抱歉,出了点问题”

    嗨 我对 Heroku 还很陌生 我已经完成了我的应用程序的一部分 目前我在本地工作 但我想部署到 Heroku 当我打字时heroku logs我懂了 2012 07 30T16 36 27 00 00 app web 1 DEPRECA
  • 在 Firebase 中创建用户时出现错误

    所以我正在关注精明的应用程序教程以学习 Vue js 本教程使用 Firebase 和 Firestore 由于 Firestore 处于 Beta 阶段 正如教程所述 因此可能会发生变化 我认为这里可能就是这种情况 无论如何 我正在尝试注
  • 在 Sweave 中制作扁平化 pdf

    因此 我正在使用 Sweave 创建 pdf 其中包含一些带有大量点的图表 我可以很好地获取 pdf 但它似乎用大量图层创建了它 因此很难在 Acrobat 或 Reader 中打开该文件 当我这样做时 我确实可以看到文档上加载的点 有没有
  • Postgres 是否提供刷新缓冲区缓存的命令?

    你好 有时我需要做一些 SQL 调优任务 我通常在我的测试数据库上做这样的测试 当我执行一条sql语句后 我想刷新包含SQL的缓冲区缓存 语句和sql结果 就像Oracle中的命令 Alter system flash buffer cac
  • 如何添加和删除CSS类

    如何删除CSS默认类 这是我的div div 这是我的 css 类 messageContainer height 26px color FFFFFF BACKGROUND COLOR 6af VERTICAL ALIGN middle T
  • 身份管理/SSO 解决方案? [关闭]

    Closed 此问题正在寻求书籍 工具 软件库等的推荐 不满足堆栈溢出指南 目前不接受答案 您对基本的集中式身份管理 SSO 服务有何建议 它必须是开源的 具有可插入的身份管理器 例如 LDAP DB openID 等 并提供一系列适当的
  • 生成新的 Nestjs 模块会导致错误:无法执行命令

    我使用带有 M1 芯片的 MacOS monterey 作为操作系统 使用以下命令安装 NestJS cli sudo npm install g nestjs cli 使用创建新的 Nest 项目时nest new message一切正常
  • 使用 XSLT 合并相邻的兄弟节点

    我有一个问题让我头疼极了 请帮我 输入是 p class section section 1 p p class code some code p p class code following code p p class code fol
  • 如何在Javascript中深度复制(克隆)具有数组成员的对象?

    介绍 我有一个班级Persons包含一个数组Person和功能 function Persons this mItems Array of Objects Person Persons prototype calculateScores f
  • JavaScript 中未声明变量的用法

    如果我们尝试使用未声明但允许为其设置值的变量 为什么 JavaScript 会抛出引用错误 e g a 10 creates global variable a and sets value to 10 even though its un
  • 使用 Maven 运行多个类

    我有一个包含多个类的包 每个类都封装了一个可执行程序 即带有 main 方法 即 com myorg examples classA com myorg examples classB etc 所有类都属于同一个包 com myorg ex
  • 为什么通过泛型类型映射闭集不允许解析重复?

    In 这段 TypeScript 代码 也在下面重复 有一个映射类型 type DRYObjectModelMap PlanetaryBodyClass in keyof FieldNameWithValueMap ObjectModel
  • 如何将分隔的字符串转换为表格布局?

    我有一个包含值的字段 CM45024 CM45025 CM45026 我想使用子报告将其分成多个项目 我的 jrxml 来源是
  • 如何对元素进行排序并将它们存储在变量中,XSLT

    我想知道是否可以先对一些元素进行排序并将它们 已排序 存储在变量中 我需要引用它们认为 XSLT 这就是为什么我想将它们存储在变量中 我试图执行以下操作 但似乎不起作用
  • 在 rspec 功能测试中使用 Devise

    我编写了以下 rspec 功能测试规范 require rails helper RSpec describe Team management type feature do user sign in describe User creat
  • PyFPDF 内部链接

    内部链接应该如何做 我尝试从第 1 页链接到第 2 页 效果很好 但从一页到第二页是行不通的 怎么了 from fpdf import FPDF pdf FPDF pdf add page pdf set font Arial B 16 t
  • Java:在运行时将类添加到 Jar 存档中

    我想在运行时将一些编译的类 class 文件 添加到当前 Jar 文件中的目录 包 我怎样才能做到这一点 Thanks 这是无法完成的 要更新 Jar 文件 您需要创建一个新文件并用新文件覆盖旧文件 以下是有关如何执行此操作的示例 impo