add Zip File - Java File Path IO

Java examples for File Path IO:Zip File

Description

add Zip File

Demo Code


//package com.java2s;
import java.io.BufferedInputStream;

import java.io.File;

import java.io.FileOutputStream;
import java.util.Enumeration;

import java.util.zip.ZipEntry;
import java.util.zip.ZipFile;

import java.util.zip.ZipOutputStream;

public class Main {
    private static final int BUFFER = 1024;
    public static final String UPDATE = "_updated";

    public static void addZipFile(File destPath, File file, String zipName)
            throws Exception {
        String name = destPath.getName();
        int index = name.lastIndexOf(".");
        String fileSuffix = "";
        if (index > 0) {
            fileSuffix = name.substring(index + 1);
            name = name.substring(0, index);
        }//from  w ww . j  a va  2  s.c o m
        ZipOutputStream zipOutputStream = new ZipOutputStream(
                new FileOutputStream(new File(destPath.getParentFile(),
                        name + UPDATE + "." + fileSuffix)));
        ZipFile zipFile = new ZipFile(destPath);
        Enumeration<? extends ZipEntry> zipEntries = zipFile.entries();
        ZipEntry cZipEntry = null;
        ZipEntry cNewZipEntry = null;
        while (zipEntries.hasMoreElements()) {
            cZipEntry = zipEntries.nextElement();
            if (!zipName.equals(cZipEntry.getName())) {
                if (cZipEntry.isDirectory()) {
                    zipOutputStream.putNextEntry(cZipEntry);
                    zipOutputStream.closeEntry();
                } else {
                    cNewZipEntry = new ZipEntry(cZipEntry.getName());
                    zipOutputStream.putNextEntry(cNewZipEntry);
                    BufferedInputStream bis = new BufferedInputStream(
                            zipFile.getInputStream(cZipEntry));
                    int count;
                    byte data[] = new byte[BUFFER];
                    while ((count = bis.read(data, 0, BUFFER)) != -1) {
                        zipOutputStream.write(data, 0, count);
                    }
                    bis.close();
                    zipOutputStream.closeEntry();
                }
            }
        }
        zipOutputStream.close();
        zipFile.close();
    }
}

Related Tutorials