Java ZipOutputStream Write zip(File[] files, String baseDir, ZipOutputStream zos)

Here you can find the source of zip(File[] files, String baseDir, ZipOutputStream zos)

Description

zip

License

Open Source License

Declaration

private static void zip(File[] files, String baseDir, ZipOutputStream zos) throws Throwable 

Method Source Code


//package com.java2s;
//License from project: Open Source License 

import java.io.BufferedInputStream;

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

import java.util.zip.CRC32;
import java.util.zip.CheckedInputStream;

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

public class Main {
    public static final int BUFFER_SIZE = 8192;

    private static void zip(File[] files, String baseDir, ZipOutputStream zos) throws Throwable {
        byte buffer[] = new byte[BUFFER_SIZE];
        for (File f : files) {
            String name = f.getAbsolutePath();
            if (name.startsWith(baseDir)) {
                name = name.substring(baseDir.length());
            }/*from w ww . j  a va2s .c  om*/
            if (name.startsWith(System.getProperty("file.separator"))) {
                name = name.substring(1);
            }
            if (f.isDirectory()) {
                zip(f.listFiles(), baseDir, zos);
            } else {
                if (name.endsWith(".DS_Store")) {
                    continue;
                }
                ZipEntry entry = new ZipEntry(name);
                entry.setSize(f.length());
                entry.setCrc(crc32(f));
                zos.putNextEntry(entry);
                BufferedInputStream is = new BufferedInputStream(new FileInputStream(f), BUFFER_SIZE);
                int count;
                try {
                    while ((count = is.read(buffer, 0, BUFFER_SIZE)) != -1) {
                        zos.write(buffer, 0, count);
                    }
                } finally {
                    is.close();
                }
                zos.closeEntry();
            }
        }
    }

    public static long crc32(File f) throws Throwable {

        CheckedInputStream cis = new CheckedInputStream(new BufferedInputStream(new FileInputStream(f)),
                new CRC32());
        try {
            while (cis.read() != -1) {
            }
            return cis.getChecksum().getValue();
        } finally {
            cis.close();
        }
    }
}

Related

  1. archiveFile(String relativePath, ZipOutputStream zos, File root)
  2. writeFolderEntry(ZipOutputStream zout, String relpath)
  3. zip(File current, String rootPath, ZipOutputStream zipStream, byte[] buffer)
  4. zip(final File directory, final File base, final ZipOutputStream zipOutputStream)
  5. zipAutoBase(File f, File base, ZipOutputStream out)
  6. zipFile(ZipOutputStream out, File file, String dir)
  7. zipFile(ZipOutputStream out, File sourceFile)