【问题标题】:Creating a JAR file programmatically以编程方式创建 JAR 文件
【发布时间】:2010-12-15 13:48:29
【问题描述】:

我从我的 java 代码创建了一个 Jar 文件:

public void create() throws IOException{
     FileOutputStream stream = new FileOutputStream(this.packagePath);
     JarOutputStream out = new JarOutputStream(stream, new Manifest());
     out.close();
     //jarFile = new JarFile(new File(this.packagePath));
}

我得到一个 META-INF 目录,里面有一个 MANIFEST.MF 文件。

现在,当我想向 jar 文件中添加文件时:

public void addFile(File file) throws IOException{

    //first, make sure the package already exists
    if(!file.exists()){
        throw new IOException("Make" +
                " sure the package file already exists.you might need to call the Package.create() " +
                "method first.");
    }

    FileOutputStream stream = new FileOutputStream(this.packagePath);
    JarOutputStream out = new JarOutputStream(stream);
    /*if(jarFile.getManifest()!=null){
        out = new JarOutputStream(stream,jarFile.getManifest());
    }else{
        out=new JarOutputStream(stream);
    }*/

    byte buffer[] = new byte[BUFFER_SIZE];     
    JarEntry jarEntry = new JarEntry(file.getName());
    jarEntry.setTime(file.lastModified());
    out.putNextEntry(jarEntry);

    //Write file to archive
    FileInputStream in = new FileInputStream(file);

    while (true) {
      int nRead = in.read(buffer, 0, buffer.length);
      if (nRead <= 0)
        break;
      out.write(buffer, 0, nRead);
    }
    in.close();     
    out.close();
}

使用上述代码将文件添加到 JAR 存档时,带有 MANIFEST.MF 的 META-INF 目录消失了,我得到了新添加的文件。

我希望能够将文件添加到 jar 中,并且仍然可以获取清单文件。在清单文件中,我想要一行包含新添加的 jar 的名称。

谢谢。

【问题讨论】:

    标签: java jar


    【解决方案1】:
    1. 在项目类路径中包含 ant.jar
    2. 代码
      Jar jar = new Jar();
      //配置jar对象
      jar.execute();

    查看here 了解您可以设置的参数。

    【讨论】:

      【解决方案2】:

      我认为您无法添加新条目,因为您无法打开“附加”的 jar 包。我认为您必须创建一个新的 jar 文件并从旧的复制条目,然后添加您的条目​​。

      【讨论】:

        【解决方案3】:
        FileOutputStream stream = new FileOutputStream(this.packagePath);
        

        这一行将创建一个新的空文件。

        要编辑 jar 文件,您需要备份旧版本并将其条目复制到新的 jar 文件中。

        【讨论】:

          猜你喜欢
          • 2011-02-26
          • 2011-01-18
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2012-03-08
          • 2018-04-13
          • 1970-01-01
          • 2012-02-07
          相关资源
          最近更新 更多