【问题标题】:Unpacking / extracting resource from another JAR file从另一个 JAR 文件中解压/提取资源
【发布时间】:2013-11-20 11:23:44
【问题描述】:

我有两个 jar 文件。通常,如果我想从我的 jar 文件中“解包”资源,我会选择:

    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 文件会怎样?我可以以类似的方式访问第二个 JAR 文件资源吗?第二个 JAR 没有运行,所以没有自己的类加载器。是解压第二个 JAR 文件的唯一方法吗?

【问题讨论】:

    标签: java jar resources


    【解决方案1】:

    如果另一个 Jar 在您的常规类路径中,那么您可以简单地以完全相同的方式访问该 jar 中的资源。如果 Jar 只是一个不在您的类路径中的文件,您将不得不打开它并使用 the JarFile and related classes 提取文件。请注意,Jar 文件只是特殊类型的 Zip 文件,因此您也可以使用 ZipFile related classes 访问 Jar 文件

    【讨论】:

      【解决方案2】:

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

            /**
         * 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) {}
              }
            }
          }
      

      【讨论】:

        【解决方案3】:

        您可以使用URLClassLoader

        URLClassLoader classLoader = new URLClassLoader(new URL[]{new URL("path_to_file//myjar.jar")})
        classLoader.loadClass("MyClass");//is requared
        InputStream stream = classLoader.getResourceAsStream("myresource.properties");
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2013-12-07
          • 1970-01-01
          • 2021-11-21
          • 2019-11-08
          相关资源
          最近更新 更多