生成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();
                }

            }
        }
    }
}

 

上一篇:Ubuntu Linux C 编程----用递归实现倒序打印


下一篇:用Java写一个备份文件的程序!