Java Zip File List zipFiles(String filesPathToZip, String pathToSave)

Here you can find the source of zipFiles(String filesPathToZip, String pathToSave)

Description

zip Files

License

Open Source License

Declaration

public static void zipFiles(String filesPathToZip, String pathToSave) throws IOException 

Method Source Code

//package com.java2s;
/*******************************************************************************
 * Licensed Materials - Property of IBM//from w ww.  j  a  va 2s.  co  m
 * ? Copyright IBM Corporation 2015. All Rights Reserved.
 * 
 * Note to U.S. Government Users Restricted Rights:
 * Use, duplication or disclosure restricted by GSA ADP Schedule
 * Contract with IBM Corp. 
 *******************************************************************************/

import java.io.File;
import java.io.FileInputStream;

import java.io.FileOutputStream;
import java.io.IOException;

import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;

public class Main {
    public static void zipFiles(String filesPathToZip, String pathToSave) throws IOException {
        File filesToZip = new File(filesPathToZip);

        ZipOutputStream zos = new ZipOutputStream(new FileOutputStream(new File(pathToSave)));
        try {
            archiveFile(null, zos, filesToZip);
        } finally {
            zos.close();
        }
    }

    public static void archiveFile(String relativePath, ZipOutputStream zos, File root) throws IOException {
        byte[] buffer = new byte[1024];

        File[] files = root.listFiles();
        for (int i = 0; i < files.length; i++) {
            File f = files[i];
            String path = null;
            if (relativePath == null) {
                path = f.getName();
            } else {
                path = relativePath + "/" + f.getName(); //$NON-NLS-1$
            }
            if (f.isDirectory()) {
                archiveFile(path, zos, f);
            } else {
                ZipEntry entry = new ZipEntry(path);
                zos.putNextEntry(entry);
                FileInputStream in = null;

                try {
                    in = new FileInputStream(f);
                    int c = -1;
                    while ((c = in.read(buffer)) != -1) {
                        zos.write(buffer, 0, c);
                    }
                    zos.closeEntry();
                } finally {
                    if (in != null) {
                        in.close();
                    }
                }
            }
        }
    }
}

Related

  1. zipFiles(List files, OutputStream os)
  2. zipFiles(List srcfile, File zipfile)
  3. ZipFiles(String destination, Vector files)
  4. zipFiles(String filename, String[] files)
  5. zipFiles(String files[], String fielPath)
  6. zipFiles(String output, String sDir, String sSearch)
  7. zipFiles(String output_dir, List files)
  8. zipFiles(String source, String target)
  9. zipFiles(String srcFolder, String destZipFile)