从另一个JAR文件解压缩/解压缩资源 [英] Unpacking / extracting resource from another JAR file

查看:143
本文介绍了从另一个JAR文件解压缩/解压缩资源的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有两个jar文件。通常,如果我想从我的jar文件中解压缩资源,我会去:

I have two jar files. Normally if I want to 'unpack' resource from my jar file I go for :

    InputStream in = MyClass.class.getClassLoader().getResourceAsStream(name);
    byte[] buffer = new byte[1024];
    int read = -1;
    File temp2 = new File(new File(System.getProperty("user.dir")), name);
    FileOutputStream fos2 = new FileOutputStream(temp2);

    while((read = in.read(buffer)) != -1) {
        fos2.write(buffer, 0, read);
    }
    fos2.close();
    in.close();

如果我在同一目录中有另一个JAR文件怎么办?我可以用simillar方式访问第二个JAR文件资源吗?第二个JAR没有运行,所以没有自己的类加载器。是解压第二个JAR文件的唯一方法吗?

What If I would have another JAR files in the same directory? Can I access the second JAR file resources in simillar way? This second JAR is not runned so don't have own class loader. Is the only way to unzip this second JAR file?

推荐答案

我使用下面提到的代码做同样的操作。它使用JarFile类来执行相同的操作。

I've used the below mentioned code to do the same kind of operation. It uses JarFile class to do the same.

      /**
   * Copies a directory from a jar file to an external directory.
   */
  public static void copyResourcesToDirectory(JarFile fromJar, String jarDir, String destDir)
      throws IOException {
    for (Enumeration<JarEntry> entries = fromJar.entries(); entries.hasMoreElements();) {
      JarEntry entry = entries.nextElement();
      if (entry.getName().startsWith(jarDir + "/") && !entry.isDirectory()) {
        File dest = new File(destDir + "/" + entry.getName().substring(jarDir.length() + 1));
        File parent = dest.getParentFile();
        if (parent != null) {
          parent.mkdirs();
        }

        FileOutputStream out = new FileOutputStream(dest);
        InputStream in = fromJar.getInputStream(entry);

        try {
          byte[] buffer = new byte[8 * 1024];

          int s = 0;
          while ((s = in.read(buffer)) > 0) {
            out.write(buffer, 0, s);
          }
        } catch (IOException e) {
          throw new IOException("Could not copy asset from jar file", e);
        } finally {
          try {
            in.close();
          } catch (IOException ignored) {}
          try {
            out.close();
          } catch (IOException ignored) {}
        }
      }
    }

这篇关于从另一个JAR文件解压缩/解压缩资源的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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