Example #1
0
  /**
   * Extract files from the <i>source</i> jar file to the <i>target</i> directory. If necessary, the
   * <i>target</i> directory is created.<br>
   * <br>
   * For example, if this method is called with a <i>source</i> of <tt>foo.jar</tt> (which contains
   * <tt>a</tt> and <tt>b</tt>) and a <i>target</i> of <tt>/bar</tt>, when this method exits
   * <tt>/bar</tt> will contain <tt>/bar/a</tt> and <tt>/bar/b</tt>.
   *
   * @param progress if non-null, this progress monitor is updated with the name of each file as it
   *     is copied.
   * @param source source jar file
   * @param target directory
   * @param saveSuffix if non-null, pre-existing files in <i>target</i> whose paths match files to
   *     be copied from <i>source</i> will be renamed to <tt>name + saveSuffix</tt>.
   * @return false if any problems were encountered.
   */
  public static final boolean copyJar(
      ProgressMonitor progress, File source, File target, String saveSuffix) {
    // if target exists, it must be a directory
    if (target.exists() && !target.isDirectory()) {
      return false;
    }

    // if the target doesn't exist yet, create it
    if (!target.exists()) {
      target.mkdirs();
    }

    // try to open the jar file
    JarFile jar;
    try {
      jar = new JarFile(source);
    } catch (IOException ioe) {
      return false;
    }

    boolean result = true;

    Enumeration en = jar.entries();
    while (en.hasMoreElements()) {
      JarEntry entry = (JarEntry) en.nextElement();

      final String entryName = entry.getName();

      // skip manifest files
      if (JarFile.MANIFEST_NAME.startsWith(entryName)) {
        continue;
      }

      File newFile = new File(target, entryName);
      newFile.mkdirs();

      if (!entry.isDirectory()) {

        InputStream in;
        try {
          in = jar.getInputStream(entry);
        } catch (IOException ioe) {
          System.err.println("Couldn't copy entry " + entryName);
          continue;
        }

        copyStreamToFile(progress, in, newFile, saveSuffix);

        try {
          in.close();
        } catch (Exception e) {;
        }
      }

      newFile.setLastModified(entry.getTime());
    }

    return result;
  }