java多文件生成zip

原文鏈接:https://www.cnblogs.com/huanshilang/p/10601712.html

注意:開關流的循序:類似棧的輸入輸出

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.List;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;

import static org.springframework.util.StreamUtils.BUFFER_SIZE;

/**
 * Author: zh
 * Desc: 壓縮包工具類
 * Date: Created in 2018/5/19 13:51
 */
public class FileToZip {

    /**
     * 把文件集合打成zip壓縮包
     * @param srcFiles 壓縮文件集合
     * @param zipFile  zip文件名
     * @throws RuntimeException 異常
     */
    public static void toZip(List<File> srcFiles, File zipFile) throws RuntimeException {
        if(zipFile == null){
            return;
        }
        if(!zipFile.getName().endsWith(".zip")){
            return;
        }
        ZipOutputStream zos = null;
        try {
            FileOutputStream out = new FileOutputStream(zipFile);
            zos = new ZipOutputStream(out);
            for (File srcFile : srcFiles) {
                byte[] buf = new byte[BUFFER_SIZE];
                zos.putNextEntry(new ZipEntry(srcFile.getName()));
                System.out.println( "srcFile.getName()"+srcFile.getName());
                int len;
                FileInputStream in = new FileInputStream(srcFile);
                while ((len = in.read(buf)) != -1) {
                    zos.write(buf, 0, len);
                }
                in.close();
                zos.closeEntry();
            }
            if (zos != null) {
                try {
                    zos.close();
                } catch (IOException e) {
                    System.out.println("ZipUtil toZip close exception" + e);
                }
            }
            out.close();
        } catch (Exception e) {
            throw new RuntimeException("zipFile error from ZipUtils", e);
        }
    }

}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章