其他分享
首页 > 其他分享> > 生成zip压缩包

生成zip压缩包

作者:互联网

package com.xiang;

import java.io.BufferedInputStream;
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 ZipWriter {
    String source;
    String zipName;

    public ZipWriter() {
        super();
        // TODO Auto-generated constructor stub
    }

    public ZipWriter(String source, String zipName) {
        super();
        this.source = source;
        this.zipName = zipName;
    }

    public void zip() throws IOException {
        System.out.println("开始压缩。。。");

        ZipOutputStream zos = new ZipOutputStream(new FileOutputStream(zipName));
        zipTemp(new File(source), zos, new File(source).getName());
        zos.close();
        System.out.println("压缩结束。。");

    }

    public void zipTemp(File file, ZipOutputStream zos, String ziptemp) throws IOException {

        System.out.println("source" + source);
        File[] files = file.listFiles();
        if (file.isDirectory() && files.length == 0) {
            System.out.println("压缩的空目录" + ziptemp + File.separator);
            // 生成目录后面要加分割符,不然无法生成。
            zos.putNextEntry(new ZipEntry(ziptemp + File.separator));

        } else {
            for (int i = 0; i < files.length; i++) {
                if (files[i].isDirectory()) {
                    zipTemp(files[i], zos, ziptemp + File.separator + files[i].getName());
                } else {
                    System.out.println("压缩的文件:" + ziptemp + File.separator + files[i].getName());
                    zos.putNextEntry(new ZipEntry(ziptemp + File.separator + files[i].getName()));
                    FileInputStream fis = new FileInputStream(files[i]);
                    BufferedInputStream bis = new BufferedInputStream(fis);
                    int len = 0;
                    byte[] bb = new byte[1024];
                    while ((len = bis.read(bb)) != -1) {
                        zos.write(bb, 0, len);
                    }
                    bis.close();
                }

            }
        }
    }
}

 

标签:files,java,zip,生成,source,zos,File,new,压缩包
来源: https://www.cnblogs.com/wenwenzuiniucha/p/14749778.html