如何使用JarOutputStream创建JAR文件? [英] How to use JarOutputStream to create a JAR file?

查看:212
本文介绍了如何使用JarOutputStream创建JAR文件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何使用 java.util.jar.JarOutputStream 以编程方式创建JAR文件?我的程序生成的JAR文件看起来是正确的(它提取正常)但是当我尝试从中加载库时,Java抱怨它无法找到明确存储在其中的文件。如果我提取JAR文件并使用Sun的 jar 命令行工具重新压缩它,那么生成的库就可以正常工作。简而言之,我的JAR文件出了问题。

How does one create a JAR file programmatically using java.util.jar.JarOutputStream? The JAR file produced by my program looks correct (it extracts fine) but when I try loading a library from it Java complains that it cannot find files which are clearly stored inside it. If I extract the JAR file and use Sun's jar command-line tool to re-compress it the resulting library works fine. In short, something is wrong with my JAR file.

请解释如何以编程方式创建JAR文件,并附带清单文件。

Please explain how to create a JAR file programmatically, complete with a manifest file.

推荐答案

事实证明 JarOutputStream 有三个未记录的怪癖:

It turns out that JarOutputStream has three undocumented quirks:


  1. 目录名称必须以'/'斜杠结尾。

  2. 路径必须使用'/'斜杠,而不是'\'

  3. 条目不能以'/'斜杠开头。

这是创建一个正确的方法Jar文件:

Here is the correct way to create a Jar file:

public void run() throws IOException
{
  Manifest manifest = new Manifest();
  manifest.getMainAttributes().put(Attributes.Name.MANIFEST_VERSION, "1.0");
  JarOutputStream target = new JarOutputStream(new FileOutputStream("output.jar"), manifest);
  add(new File("inputDirectory"), target);
  target.close();
}

private void add(File source, JarOutputStream target) throws IOException
{
  BufferedInputStream in = null;
  try
  {
    if (source.isDirectory())
    {
      String name = source.getPath().replace("\\", "/");
      if (!name.isEmpty())
      {
        if (!name.endsWith("/"))
          name += "/";
        JarEntry entry = new JarEntry(name);
        entry.setTime(source.lastModified());
        target.putNextEntry(entry);
        target.closeEntry();
      }
      for (File nestedFile: source.listFiles())
        add(nestedFile, target);
      return;
    }

    JarEntry entry = new JarEntry(source.getPath().replace("\\", "/"));
    entry.setTime(source.lastModified());
    target.putNextEntry(entry);
    in = new BufferedInputStream(new FileInputStream(source));

    byte[] buffer = new byte[1024];
    while (true)
    {
      int count = in.read(buffer);
      if (count == -1)
        break;
      target.write(buffer, 0, count);
    }
    target.closeEntry();
  }
  finally
  {
    if (in != null)
      in.close();
  }
}

这篇关于如何使用JarOutputStream创建JAR文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆