Explode source JAR and/or ZIP files into a target directory

@param zipFiles
source files
@param jarFiles
source files
@param destDir
target directory (should already exist)
@exception IOException
error creating a target file
355497
public void process(File[] zipFiles, File[] jarFiles, File destDir) throws IOException {
        processZips(zipFiles, destDir);
        processJars(jarFiles, destDir);
    }
1353948
public static byte[] zip(List<String> fileNames, List<byte[]> fileContents) throws IOException {

        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        // Create the ZIP file
        ZipOutputStream out = new ZipOutputStream(baos);

        for (int i=0, size=fileNames.size(); i<size; i++) {
            String name = fileNames.get(i);
            byte[] content = fileContents.get(i);

            // Add ZIP entry to output stream.
            ZipEntry entry = new ZipEntry(name);
            entry.setSize(content.length);            
            out.putNextEntry(entry);
            out.write(content);
            // Complete the entry
            out.closeEntry();
        }
        out.close();
        return baos.toByteArray();
    }
255227
public static void main(final String[] args) {
        if (args.length == 0) {
            printHelp();
            System.exit(0);
        }
        List<String> zipNames = new ArrayList<String>();
        List<String> jarNames = new ArrayList<String>();
        String destDir = null;
        boolean jarActive = false, zipActive = false, destDirActive = false;
        boolean verbose = false;
        // process arguments
        for (int i = 0; i < args.length; i++) {
            String arg = args[i];
            if (arg.charAt(0) == '-') { // switch
                arg = arg.substring(1);
                if (arg.equalsIgnoreCase("jar")) {
                    jarActive = true;
                    zipActive = false;
                    destDirActive = false;
                } else if (arg.equalsIgnoreCase("zip")) {
                    zipActive = true;
                    jarActive = false;
                    destDirActive = false;
                } else if (arg.equalsIgnoreCase("dir")) {
                    jarActive = false;
                    zipActive = false;
                    destDirActive = true;
                } else if (arg.equalsIgnoreCase("verbose")) {
                    verbose = true;
                } else {
                    reportError("Invalid switch - " + arg);
                }
            } else {
                if (jarActive) {
                    jarNames.add(arg);
                } else if (zipActive) {
                    zipNames.add(arg);
                } else if (destDirActive) {
                    if (destDir != null) {
                        reportError("duplicate argument - " + "-destDir");
                    }
                    destDir = arg;
                } else {
                    reportError("Too many parameters - " + arg);
                }
            }
        }
        if (destDir == null || (zipNames.size() + jarNames.size()) == 0) {
            reportError("Missing parameters");
        }
        if (verbose) {
            System.out.println("Effective command: " + ZipExploder.class.getName() + " " + (jarNames.size() > 0 ? "-jars " + jarNames + " " : "")
                    + (zipNames.size() > 0 ? "-zips " + zipNames + " " : "") + "-dir " + destDir);
        }
        try {
            ZipExploder ze = new ZipExploder(verbose);
            ze.process(FileUtils.pathNamesToFiles(zipNames.toArray(new String[zipNames.size()])), FileUtils.pathNamesToFiles(jarNames.toArray(new String[jarNames.size()])), new File(destDir));
        } catch (IOException ioe) {
            System.err.println("Exception - " + ioe.getMessage());
            ioe.printStackTrace(); // *** debug ***
            System.exit(2);
        }
    }
79505
public static void zipFile(File input, File output) throws IOException {
		try (FileOutputStream fos = new FileOutputStream(output)) {
			zipFile(input, fos);
		}
	}
574644
public static void create(String zipFilename, String... filenames)
            throws IOException {

        try (FileSystem zipFileSystem = createZipFileSystem(zipFilename, true)) {
            final Path root = zipFileSystem.getPath("/");

            //iterate over the files we need to add
            for (String filename : filenames) {
                final Path src = Paths.get(filename);

                //add a file to the zip file system
                if(!Files.isDirectory(src)){
                    final Path dest = zipFileSystem.getPath(root.toString(),
                            src.toString());
                    final Path parent = dest.getParent();
                    if(Files.notExists(parent)){
                        if(logger.isDebugEnabled()) logger.debug("Creating directory %s", parent);
                        Files.createDirectories(parent);
                    }
                    Files.copy(src, dest, StandardCopyOption.REPLACE_EXISTING);
                }
                else{
                    //for directories, walk the file tree
                    Files.walkFileTree(src, new SimpleFileVisitor<Path>(){
                        @Override
                        public FileVisitResult visitFile(Path file,
                                                         BasicFileAttributes attrs) throws IOException {
                            final Path dest = zipFileSystem.getPath(root.toString(),
                                    file.toString());
                            Files.copy(file, dest, StandardCopyOption.REPLACE_EXISTING);
                            return FileVisitResult.CONTINUE;
                        }

                        @Override
                        public FileVisitResult preVisitDirectory(Path dir,
                                                                 BasicFileAttributes attrs) throws IOException {
                            final Path dirToCreate = zipFileSystem.getPath(root.toString(),
                                    dir.toString());
                            if(Files.notExists(dirToCreate)){
                                if(logger.isDebugEnabled()) logger.debug("Creating directory %s\n", dirToCreate);
                                Files.createDirectories(dirToCreate);
                            }
                            return FileVisitResult.CONTINUE;
                        }
                    });
                }
            }
        }
    }
1361024
private static FileSystem createZipFileSystem(String zipFilename, boolean create) throws IOException {

        // convert the filename to a URI
        final Path path = Paths.get(zipFilename);
        if(Files.notExists(path.getParent())) {
            Files.createDirectories(path.getParent());
        }
        final URI uri = URI.create("jar:file:" + path.toUri().getPath());

        final Map<String, String> env = new HashMap<>();
        if (create) {
            env.put("create", "true");
        }
        return FileSystems.newFileSystem(uri, env);
    }
587252
public void unzip(final ZipFile zipFile, final File toDir) throws IOException
	{
		ZipExtensions.unzip(zipFile, toDir);
	}
220390
public static void compress(File dir, File zipFile) throws IOException {

    FileOutputStream fos = new FileOutputStream(zipFile);
    ZipOutputStream zos = new ZipOutputStream(fos);

    recursiveAddZip(dir, zos, dir);

    zos.finish();
    zos.close();

  }
44265
public static void copyDirectories(String[] directories, String[] destinationDirectories) throws IOException {
        copyDirectories(getFiles(directories), getFiles(destinationDirectories));
    }
30842
public void zip(final File zipFile) throws IOException {
		File[] files = listFiles();
		if (files.length == 0) {
			return;
		}
		LOG.info("Creating zip file " + zipFile + " from directory " + this);
		ZipOutputStream zipOut = null;
		try {
			zipOut = new ZipOutputStream(new FileOutputStream(zipFile));
			for (File file : files) {
				zip("", file, zipOut);
			}
		} finally {
			IOUtils.closeQuietly(zipOut);
		}
	}
609780
private synchronized static void unzip(InputStream zipFileInputStream, String destinationDir) throws IOException {
        // Create output directory if it doesn't exist
        File dir = new File(destinationDir);
        if (!dir.exists()) dir.mkdirs();

        // Buffer for read and write data to file
        byte[] buffer = new byte[1024];
        ZipInputStream zis = new ZipInputStream(zipFileInputStream);
        ZipEntry ze = zis.getNextEntry();
        while (ze != null) {
            String fileName = ze.getName();
            File newFile = new File(destinationDir + File.separator + fileName);

            // Check if it's a Directory entry
            if (ze.isDirectory()) {
                newFile.mkdirs();
            } else {
                // Save file to disk
                FileOutputStream fos = new FileOutputStream(newFile);
                int len;
                while ((len = zis.read(buffer)) > 0) {
                    fos.write(buffer, 0, len);
                }
                fos.close();
            }

            // Close current entry and move to next entry
            zis.closeEntry();
            ze = zis.getNextEntry();
        }

        // Close last entry
        zis.closeEntry();
        zis.close();
    }
671784
public static void zip(File[] sources, File target) throws IOException {
		zip(sources, target, null);
	}
541104
public static void unzip(InputStream is, File destDir)
            throws FileNotFoundException, IOException {
        BufferedOutputStream dest = null;
        ZipInputStream zis = new ZipInputStream(new BufferedInputStream(is));
        ZipEntry entry;
        while ((entry = zis.getNextEntry()) != null) {
            //System.out.println("Extracting: " + entry);
            if (entry.isDirectory()) {
                // Otherwise, empty directories do not get created
                (new File(destDir, entry.getName())).mkdirs();
            } else {
                File f = new File(destDir, entry.getName());
                f.getParentFile().mkdirs();
                int count;
                byte data[] = new byte[BUFFER];
                // write the files to the disk
                FileOutputStream fos = new FileOutputStream(f);
                dest = new BufferedOutputStream(fos, BUFFER);
                while ((count = zis.read(data, 0, BUFFER)) != -1) {
                    dest.write(data, 0, count);
                }
                dest.flush();
                dest.close();
            }
        }
        zis.close();
    }
1278787
private void zipDirectory(String zipFile, String dirToZip) {
    File directory = new File(dirToZip);
    try (ZipOutputStream stream = new ZipOutputStream(new FileOutputStream(zipFile))) {
      addDirectoryToZip(directory, directory, stream);
    } catch (Exception e) {
      throw new PlatformManagerException("Failed to zip module", e);
    }
  }
125560
public void unjarDir(File jarFile, File destDir) throws IOException {
		BufferedOutputStream dest = null;
		FileInputStream fis = new FileInputStream(jarFile);
		unjar(fis, destDir);
	}
15866
public static void compress(String folderPath, String zipFilePath) throws IOException {
    File folder = new File(folderPath);
    if (!folder.exists() || !folder.isDirectory()) {
      throw new IOException("Folder " + folderPath + " does't exist or isn't a directory");
    }

    File zipFile = new File(zipFilePath);
    if (!zipFile.exists()) {
      File zipFolder = zipFile.getParentFile();
      if (!zipFolder.exists()) {
        if (!zipFolder.mkdirs()) {
          throw new IOException("Zip folder " + zipFolder.getAbsolutePath() + " not created");
        }
      }
      if (!zipFile.createNewFile()) {
        throw new IOException("Zip file " + zipFilePath + " not created");
      }
    }

    BufferedInputStream bis;
    ZipOutputStream zos = new ZipOutputStream(
        new BufferedOutputStream(new FileOutputStream(zipFile)));
    try {
      final int BUFFER_SIZE = 8 * 1024; // 8K
      byte buffer[] = new byte[BUFFER_SIZE];
      for (String fileName : folder.list()) {
        if (fileName.equals(".") || fileName.equals("..")) {
          continue;
        }

        File file = new File(folder, fileName);
        if (!file.isFile()) {
          continue;
        }

        FileInputStream fis = new FileInputStream(file);
        bis = new BufferedInputStream(fis, BUFFER_SIZE);
        try {
          ZipEntry entry = new ZipEntry(fileName);
          zos.putNextEntry(entry);
          int count;
          while ((count = bis.read(buffer, 0, BUFFER_SIZE)) != -1) {
            zos.write(buffer, 0, count);
          }
        } finally {
          try {
            bis.close();
          } catch (IOException e) {
            // Ignore
          }
        }
      }
    } finally {
      try {
        zos.close();
      } catch (IOException e) {
        // Ignore
      }
    }
  }
900308
public static File zip(File zipFile, String[] paths, InputStream[] ins, Charset charset) throws UtilException {
		if (ArrayUtil.isEmpty(paths) || ArrayUtil.isEmpty(ins)) {
			throw new IllegalArgumentException("Paths or ins is empty !");
		}
		if (paths.length != ins.length) {
			throw new IllegalArgumentException("Paths length is not equals to ins length !");
		}

		ZipOutputStream out = null;
		try {
			out = getZipOutputStream(zipFile, charset);
			for (int i = 0; i < paths.length; i++) {
				addFile(ins[i], paths[i], out);
			}
		} finally {
			IoUtil.close(out);
		}
		return zipFile;
	}