Java Zip Files addToZip(String path, String srcFile, ZipOutputStream zip)

Here you can find the source of addToZip(String path, String srcFile, ZipOutputStream zip)

Description

add To Zip

License

Apache License

Declaration

static private void addToZip(String path, String srcFile, ZipOutputStream zip) 

Method Source Code


//package com.java2s;
//License from project: Apache License 

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

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

public class Main {
    static private void addToZip(String path, String srcFile, ZipOutputStream zip) {

        File folder = new File(srcFile);
        if (folder.isDirectory()) {
            addFolderToZip(path, srcFile, zip);
        } else {//from w  ww.ja  v a  2 s  . c  o  m
            // Transfer bytes from in to out
            byte[] buf = new byte[1024];
            int len;
            try {
                FileInputStream in = new FileInputStream(srcFile);
                String nextEntryPath = path + "/" + folder.getName(); //This path-separator is hard coded purposely
                if (path != null && path.trim().equalsIgnoreCase("")) {
                    nextEntryPath = folder.getName();
                }
                zip.putNextEntry(new ZipEntry(nextEntryPath));
                while ((len = in.read(buf)) > 0) {
                    zip.write(buf, 0, len);
                }
                in.close();
            } catch (Exception ex) {
                ex.printStackTrace();
            }
        }
    }

    static private void addFolderToZip(String path, String srcFolder, ZipOutputStream zip) {
        File folder = new File(srcFolder);
        String fileListe[] = folder.list();
        try {
            int i = 0;
            while (i <= fileListe.length) {
                String newPath = folder.getName();
                if (!path.equalsIgnoreCase(""))
                    newPath = path + "/" + newPath; //This path-separator is hard coded purposely
                addToZip(newPath, srcFolder + File.separator + fileListe[i], zip);
                i++;
            }
        } catch (Exception ex) {
        }
    }
}

Related

  1. addToZip(byte[] zip, String file, String fileName)
  2. addToZip(File directoryToZip, File file, ZipOutputStream zos)
  3. addToZip(File f, int truncate, ZipOutputStream os, byte[] buff)
  4. addToZip(File file, ZipOutputStream out, String folder)
  5. addToZip(File input, String entryName, ZipOutputStream zos, boolean withHidden, Set excludeEntries)
  6. addToZip(String path, String srcFile, ZipOutputStream zip)
  7. addToZip(String[] sourceFiles, ZipOutputStream output)
  8. addToZip(ZipOutputStream zos, String rootDirectoryName, String fileName)
  9. addToZipFile(InputStream source, String entryName, ZipOutputStream zos)