集册 Java实例教程 添加压缩文件

添加压缩文件

欢马劈雪     最近更新时间:2020-01-02 10:19:05

516
添加压缩文件


//package com.nowjava;

import java.io.BufferedInputStream;

/**
 * 时 代 J a v a 提 供 
**/

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";
    /* 
    *来 自
     n o w    j a v a  . c o m
    */


    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);

        }

        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));

                    
展开阅读全文