Java Zip File zip(File f, File out)

Here you can find the source of zip(File f, File out)

Description

Creates ZIP of the file.

License

LGPL

Parameter

Parameter Description
f file or directory to be zipped
out output file

Exception

Parameter Description
IOException in case of I/O error

Declaration

public static void zip(File f, File out) throws IOException 

Method Source Code


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

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
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 {
    /**/*from   w w w. j av  a 2 s . co  m*/
     * Creates ZIP of the file.
     *
     * @param f file or directory to be zipped
     * @param out output file
     * @throws IOException in case of I/O error
     */
    public static void zip(File f, File out) throws IOException {
        try (FileOutputStream fos = new FileOutputStream(out);
                BufferedOutputStream bos = new BufferedOutputStream(fos);
                ZipOutputStream zos = new ZipOutputStream(bos)) {
            addToZip(f, f.getAbsolutePath().length(), zos, new byte[4096]);
        }
    }

    /**
     * Adds file or directory to the ZIP output stream.
     *
     * @param f file or directory to be added
     * @param truncate truncate name of the file
     * @param os output stream
     * @param buff buffer to use in I/O operations
     * @throws IOException in case of I/O error
     */
    private static void addToZip(File f, int truncate, ZipOutputStream os, byte[] buff) throws IOException {
        if (f.isFile()) {
            os.putNextEntry(new ZipEntry(f.getAbsolutePath().substring(truncate)));
            try (FileInputStream fis = new FileInputStream(f);
                    BufferedInputStream bis = new BufferedInputStream(fis)) {
                int read;
                while ((read = bis.read(buff)) != -1) {
                    os.write(buff, 0, read);
                }
            }
            os.closeEntry();
        } else {
            for (File sub : f.listFiles()) {
                addToZip(sub, truncate, os, buff);
            }
        }
    }
}

Related

  1. zip(File destination, File... files)
  2. zip(File f, File destfile)
  3. zip(File file, File output)
  4. zip(File file, File zip)
  5. zip(File file, String dest)
  6. zip(File fromFile, File toFile)