create Zip File - Java File Path IO

Java examples for File Path IO:Zip File

Description

create Zip File

Demo Code


//package com.java2s;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;

import java.util.zip.ZipEntry;
import java.util.zip.ZipException;

import java.util.zip.ZipOutputStream;

public class Main {
    private static final int BUFFER = 2048;

    public static void createZipFile(String path, String zipName) {
        File dir = new File(path);

        String[] list = dir.list();
        String _path;//from  www  . j  av  a2 s  .c  o m

        if (!dir.canRead() || !dir.canWrite())
            return;

        int len = list.length;

        if (path.charAt(path.length() - 1) != '/')
            _path = path + "/";
        else
            _path = path;

        try {
            ZipOutputStream zip_out = new ZipOutputStream(
                    new BufferedOutputStream(new FileOutputStream(zipName),
                            BUFFER));

            for (int i = 0; i < len; i++)
                zip_folder(new File(_path + list[i]), zip_out);

            zip_out.close();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public static void zip_folder(File file, ZipOutputStream zout)
            throws ZipException, IOException {
        byte[] data = new byte[BUFFER];
        int read;

        if (file.isFile()) {
            ZipEntry entry = new ZipEntry(file.getName());
            zout.putNextEntry(entry);
            BufferedInputStream instream = new BufferedInputStream(
                    new FileInputStream(file));

            while ((read = instream.read(data, 0, BUFFER)) != -1)
                zout.write(data, 0, read);

            zout.closeEntry();
            instream.close();

        } else if (file.isDirectory()) {
            String[] list = file.list();
            int len = list.length;

            for (int i = 0; i < len; i++)
                zip_folder(new File(file.getPath() + "/" + list[i]), zout);
        }
    }
}

Related Tutorials