java 把檔案壓縮成 zip

FH-Admin發表於2021-09-16
package org.fh.util;

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

/**
 * 說明:java壓縮成zip
 * 作者:FH Admin
 * from:fhadmin.cn
 */
public class FileZip {

    /**
     * @param inputFileName 你要壓縮的資料夾(整個完整路徑)
     * @param zipFileName 壓縮後的檔案(整個完整路徑)
     * @throws Exception
     */
    public static Boolean zip(String inputFileName, String zipFileName) throws Exception {
        zip(zipFileName, new File(inputFileName));
        return true;
    }

    private static void zip(String zipFileName, File inputFile) throws Exception {
        ZipOutputStream out = new ZipOutputStream(new FileOutputStream(zipFileName));
        zip(out, inputFile, "");
        out.flush();
        out.close();
    }

    private static void zip(ZipOutputStream out, File f, String base) throws Exception {
        if (f.isDirectory()) {
            File[] fl = f.listFiles();
            out.putNextEntry(new ZipEntry(base + "/"));
            base = base.length() == 0 ? "" : base + "/";
            for (int i = 0; i < fl.length; i++) {
                zip(out, fl[i], base + fl[i].getName());
            }
        } else {
            out.putNextEntry(new ZipEntry(base));
            FileInputStream in = new FileInputStream(f);
            int b;
            while ((b = in.read()) != -1) {
                out.write(b);
            }
            in.close();
        }
    }

     public static void main(String [] temp){       
         try {           
             zip("E:\\ftl","E:\\test.zip");//你要壓縮的資料夾      和  壓縮後的檔案 
             }catch (Exception ex) {       
                 ex.printStackTrace();    
             }   
        }
}
本作品採用《CC 協議》,轉載必須註明作者和本文連結

相關文章