Java Zip Files addToZip(ZipOutputStream zos, String rootDirectoryName, String fileName)

Here you can find the source of addToZip(ZipOutputStream zos, String rootDirectoryName, String fileName)

Description

add To Zip

License

Open Source License

Declaration

public static void addToZip(ZipOutputStream zos, String rootDirectoryName, String fileName) throws IOException 

Method Source Code

//package com.java2s;

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

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

public class Main {
    /**//from   w w w.j  a v  a  2 s .  c  o m
     * Tweaked optimal size for speed in buffer
     */
    private static final int BUFFER_SIZE = 8 * 1024;

    public static void addToZip(ZipOutputStream zos, String rootDirectoryName, String fileName) throws IOException {

        /**
         * Get the files for the given directory
         */
        byte[] buf = new byte[BUFFER_SIZE];
        File d = new File(rootDirectoryName + fileName);

        if (d.isDirectory()) {
            for (File file : d.listFiles()) {
                if (file.isDirectory()) {
                    addToZip(zos, rootDirectoryName, fileName + file.getName() + File.separator);
                    continue;
                }

                FileInputStream fis = new FileInputStream(file.getAbsolutePath());
                ZipEntry entry = new ZipEntry(fileName + file.getName());
                zos.putNextEntry(entry);
                int len;
                while ((len = fis.read(buf)) > 0) {
                    zos.write(buf, 0, len);
                }
                zos.closeEntry();
                fis.close();
            }
        } else {

            FileInputStream fis = new FileInputStream(d.getAbsolutePath());
            ZipEntry entry = new ZipEntry(d.getName());
            zos.putNextEntry(entry);
            int len;
            while ((len = fis.read(buf)) > 0) {
                zos.write(buf, 0, len);
            }
            zos.closeEntry();
            fis.close();
        }
    }
}

Related

  1. addToZip(File file, ZipOutputStream out, String folder)
  2. addToZip(File input, String entryName, ZipOutputStream zos, boolean withHidden, Set excludeEntries)
  3. addToZip(String path, String srcFile, ZipOutputStream zip)
  4. addToZip(String path, String srcFile, ZipOutputStream zip)
  5. addToZip(String[] sourceFiles, ZipOutputStream output)
  6. addToZipFile(InputStream source, String entryName, ZipOutputStream zos)
  7. addToZipFile(String fileName, ZipOutputStream zos)
  8. fileToZip(File file, File zipFile)
  9. fileToZipFile(File toZip, File output)