java 壓縮包工具類

package com.tools;

import java.io.*;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;

public class ZipCompress {
    private String zipFileName;
    private String sourceFileName;

    public ZipCompress(String zipFileName, String sourceFileName) {
        this.zipFileName = zipFileName;
        this.sourceFileName = sourceFileName;
    }

    public  void zip( )
            throws RuntimeException {
        ZipOutputStream zos = null;
        try {
            zos = new ZipOutputStream(new FileOutputStream(zipFileName));
            java.io.File sourceFile = new java.io.File(sourceFileName);
            compress(sourceFile, zos, sourceFile.getName());
            System.out.println("壓縮完成" );
        } catch (Exception e) {
            throw new RuntimeException("zip error from ZipCompress", e);
        } finally {
            if (zos != null) {
                try {
                    zos.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }

    }

    /**
     * 遞歸壓縮方法
     *
     * @param sourceFile       源文件
     * @param zos              zip輸出流
     * @param name             壓縮後的名稱
     * @throws Exception
     */
    private static void compress(java.io.File sourceFile, ZipOutputStream zos, String name) throws Exception {
        byte[] buf = new byte[2 * 1024];
        if (sourceFile.isFile()) {
            zos.putNextEntry(new ZipEntry(name));
            int len;
            FileInputStream in = new FileInputStream(sourceFile);
            while ((len = in.read(buf)) != -1) {
                zos.write(buf, 0, len);
            }
            zos.closeEntry();
            in.close();
        } else {
            java.io.File[] listFiles = sourceFile.listFiles();
            if (listFiles == null || listFiles.length == 0) {
                zos.putNextEntry(new ZipEntry(name + "/"));
                zos.closeEntry();

            } else {
                for (java.io.File file : listFiles) {
                    compress(file, zos, name + "/" + file.getName());
                }
            }
        }
    }
}

調用java

//filePath 生成壓縮包的地址
String filePath = 前綴地址 + 名稱+ ".zip";
File zip = new File(filePath);
zip.deleteOnExit();
//path 須要壓縮的文件夾
ZipCompress zipCompress = new ZipCompress(filePath, path);
try {
    zipCompress.zip();
} catch (Exception e) {
    e.printStackTrace();
}
相關文章
相關標籤/搜索