Java中使用ZIP压缩文件

Eave 2017.11.15 10:52
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;

class Zip
{
    public static void main(String[] args) throws Exception
    {
        Zip.doZip("D:\\postnl", "D:\\postnl.zip");
    }

    public static void doZip(String sourceFileName, String zipFileName) throws Exception
    {
        // 创建zip输出流
        ZipOutputStream zipOutputStream = new ZipOutputStream(new FileOutputStream(zipFileName));
        // 创建缓冲输出流
        BufferedOutputStream bufferedOutputStream = new BufferedOutputStream(zipOutputStream);
        File file = new File(sourceFileName);
        // 调用函数
        compress(zipOutputStream, bufferedOutputStream, file, file.getName());
        bufferedOutputStream.close();
        zipOutputStream.close();
    }

    private static void compress(ZipOutputStream zipOutputStream, BufferedOutputStream bufferedOutputStream, File sourceFile, String base) throws Exception
    {
        // 如果路径为目录(文件夹)
        if(sourceFile.isDirectory())
        {

            // 取出文件夹中的文件(或子文件夹)
            File[] flist = sourceFile.listFiles();

            // 如果文件夹为空,则只需在目的地zip文件中写入一个目录进入点
            if(flist.length == 0)
            {
                zipOutputStream.putNextEntry(new ZipEntry(base + "/") );
            }
            // 如果文件夹不为空,则递归调用compress,文件夹中的每一个文件(或文件夹)进行压缩
            else
            {
                for(int i = 0;i < flist.length; i++)
                {
                    compress(zipOutputStream, bufferedOutputStream, flist[i], base + "/" + flist[i].getName());
                }
            }
        }
        // 如果不是目录(文件夹),即为文件,则先写入目录进入点,之后将文件写入zip文件中
        else
        {
            zipOutputStream.putNextEntry(new ZipEntry(base));
            FileInputStream fileInputStream = new FileInputStream(sourceFile);
            BufferedInputStream bufferedInputStream = new BufferedInputStream(fileInputStream);

            int tag;
            // 将源文件写入到zip文件中
            while((tag = bufferedInputStream.read()) != -1)
            {
                bufferedOutputStream.write(tag);
            }
            bufferedInputStream.close();
            fileInputStream.close();
        }
    }
}