zip Directory - Java java.lang

Java examples for java.lang:byte Array Compress

Description

zip Directory

Demo Code


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

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

public class Main {
    private static final int BUFFER_SIZE = 1024;

    private static void zipDirectory(ZipOutputStream zos, File inFile) {
        if (zos == null) {
            return;
        }//from   w ww . j  av  a 2s .c  om
        if (inFile == null || !inFile.exists() || !inFile.isDirectory()) {
            return;
        }
        File[] files = inFile.listFiles();
        if (files == null) {
            return;
        }
        for (File file : files) {
            if (file != null) {
                if (file.isFile()) {
                    zipFile(zos, file);
                } else {
                    zipDirectory(zos, file);
                }
            }
        }
    }

    private static void zipFile(ZipOutputStream zos, File inFile) {
        if (zos == null) {
            return;
        }
        if (inFile == null || !inFile.exists() || inFile.isDirectory()) {
            return;
        }
        BufferedInputStream bis = null;
        try {
            bis = new BufferedInputStream(new FileInputStream(inFile));
            zos.putNextEntry(new ZipEntry(inFile.getPath()));
            byte[] buffer = new byte[BUFFER_SIZE];
            int readLength = 0;
            while ((readLength = bis.read(buffer)) > 0) {
                zos.write(buffer, 0, readLength);
            }
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } catch (IllegalArgumentException e) {
            e.printStackTrace();
        } finally {
            if (bis != null) {
                try {
                    bis.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}

Related Tutorials