JAVA ZIP文件壓縮

方法一(博主推薦使用):

採用:

import org.apache.tools.zip.ZipEntry;
import org.apache.tools.zip.ZipOutputStream;

進行壓縮處理

package com.ssh.weixin.util;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import org.apache.tools.zip.ZipEntry;
import org.apache.tools.zip.ZipOutputStream;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * zip壓縮工具包
 * @Class ZipUtils
 */
public class ZipUtil {

    private final static Logger logger = LoggerFactory.getLogger(ZipUtil.class);

    private static final int BUFFER_SIZE = 2 * 1024;

    /**
     * 壓縮成ZIP
     * @param srcFilePath 壓縮文件路徑
     * @param tarFilePath 目標ZIP輸出路徑
     * @param KeepDirStructure 是否保留原來的目錄結構,true:保留目錄結構;
     *            false:所有文件跑到壓縮包根目錄下(注意:不保留目錄結構可能會出現同名文件,會壓縮失敗)
     * @throws Exception 壓縮失敗會拋出異常
     */
    public static boolean toZip(String srcFilePath, String tarFilePath, boolean KeepDirStructure) throws Exception {
        boolean isCompressSuccess = false;
        long start = System.currentTimeMillis();
        FileOutputStream fos = null;
        ZipOutputStream zos = null;
        try {
            File sourceFile = new File(srcFilePath);
            if (!sourceFile.exists()) {
                throw new FileNotFoundException("待壓縮文件 [" + srcFilePath + "]不存在.");
            }
            fos = new FileOutputStream(new File(tarFilePath));
            zos = new ZipOutputStream(fos);
            // 設置壓縮的編碼,解決壓縮路徑中的中文亂碼問題
            zos.setEncoding("GBK");     
            String fileName=sourceFile.getName();
            compress(sourceFile, zos, new String(fileName.getBytes(),"GBK"), KeepDirStructure);
            isCompressSuccess = true;
            long end = System.currentTimeMillis();
            logger.info("【文件壓縮】 壓縮完成,耗時:{} ms", (end - start));
        } catch (Exception e) {
            logger.error("【文件壓縮】 壓縮失敗", e);
            throw new RuntimeException("文件壓縮失敗", e);
        } finally {
            closeOutPutStream(zos);
            closeOutPutStream(fos);
        }
        return isCompressSuccess;
    }

    /**
     * 遞歸壓縮方法
     * @param sourceFile 源文件
     * @param zos zip輸出流
     * @param name 壓縮後的名稱
     * @param KeepDirStructure 是否保留原來的目錄結構,true:保留目錄結構;
     *            false:所有文件跑到壓縮包根目錄下(注意:不保留目錄結構可能會出現同名文件,會壓縮失敗)
     * @throws Exception
     */
    private static void compress(File sourceFile, ZipOutputStream zos, String name, boolean KeepDirStructure)
            throws Exception {
        byte[] buf = new byte[BUFFER_SIZE];
        if (sourceFile.isFile()) {
            // 向zip輸出流中添加一個zip實體,構造器中name爲zip實體的文件的名字
            zos.putNextEntry(new ZipEntry(name));
            // copy文件到zip輸出流中
            int len;
            FileInputStream in = new FileInputStream(sourceFile);
            while ((len = in.read(buf)) != -1) {
                zos.write(buf, 0, len);
            }
            zos.closeEntry();
            in.close();
        } else {
            File[] listFiles = sourceFile.listFiles();
            if (listFiles == null || listFiles.length == 0) {
                // 需要保留原來的文件結構時,需要對空文件夾進行處理
                if (KeepDirStructure) {
                    // 空文件夾的處理
                    zos.putNextEntry(new ZipEntry(name + "/"));
                    // 沒有文件,不需要文件的copy
                    zos.closeEntry();
                }
            } else {
                for (File file : listFiles) {
                    // 判斷是否需要保留原來的文件結構
                    if (KeepDirStructure) {
                        // 注意:file.getName()前面需要帶上父文件夾的名字加一斜槓,
                        // 不然最後壓縮包中就不能保留原來的文件結構,即:所有文件都跑到壓縮包根目錄下了
                        compress(file, zos, name + "/" + file.getName(), KeepDirStructure);
                    } else {
                        compress(file, zos, file.getName(), KeepDirStructure);
                    }
                }
            }
        }
    }

    /**
     * 釋放資源
     * @Title closeOutPutStream
     * @param ops
     * @return void
     */
    public static void closeOutPutStream(OutputStream ops) {
        if (ops != null) {
            try {
                ops.close();
            } catch(IOException ex) {
                logger.error("關閉輸出流失敗", ex);
            }
        }
    }
    
    public static void main(String[] args) {
    	try {
			toZip("D:\\insuredfiles\\20200519153134","D:\\insuredfiles\\20200519153134.zip",false);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

}

方法二:

採用

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

進行壓縮處理

package com.ssh.weixin.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
 * @author BYL
 * 創建時間:2015年1月14日
 */
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;
			//System.out.println(base);
			while ((b = in.read()) != -1) {
				out.write(b);
			}
			in.close();
		}
	}
	
	 public static void main(String [] temp){       
		 try {           
			 zip("D:\\imgs\\001","D:\\imgs\\imgs.zip");//你要壓縮的文件夾      和  壓縮後的文件 
			 }catch (Exception ex) {       
				 ex.printStackTrace();    
			 }   
		}
}



//=====================文件壓縮=========================
/*//把文件壓縮成zip
File zipFile = new File("E:/demo.zip");
//定義輸入文件流
InputStream input = new FileInputStream(file);
//定義壓縮輸出流	
ZipOutputStream zipOut = null;
//實例化壓縮輸出流,並制定壓縮文件的輸出路徑  就是E盤下,名字叫 demo.zip
zipOut = new ZipOutputStream(new FileOutputStream(zipFile));
zipOut.putNextEntry(new ZipEntry(file.getName()));
//設置註釋
zipOut.setComment("www.demo.com");
int temp = 0;
while((temp = input.read()) != -1) {
	zipOut.write(temp);	
}		
input.close();
zipOut.close();*/
//==============================================

 

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