注册 X
我已阅读并同意  服务条款
首页 > IT技术笔记 > 查看笔记

java压缩和解压zip

使用zip4j压缩和解压

maven项目增加依赖:

<dependency>

    <groupId>net.lingala.zip4j</groupId>

    <artifactId>zip4j</artifactId>

    <version>1.3.2</version>

</dependency>


压缩解压工具类:

点击复制

package com.explorer.utils;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import net.lingala.zip4j.core.ZipFile;
import net.lingala.zip4j.exception.ZipException;
import net.lingala.zip4j.model.FileHeader;
import net.lingala.zip4j.model.ZipParameters;
import net.lingala.zip4j.util.Zip4jConstants;

import java.io.*;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.List;

/**
 * <p>zip 工具类</p> 
 *
 * <p>依赖:zip4j</p> 
 * 
 */
public class ZipUtil {
    
    private static final Logger logger = LoggerFactory.getLogger(ZipUtil.class);

    private static String getEncoding( String path ) throws Exception{
        String encoding = "GBK" ;
        ZipFile zipFile = new ZipFile( path ) ;
        zipFile.setFileNameCharset( encoding ) ;
        List<FileHeader> list = zipFile.getFileHeaders() ;
        for( int i = 0; i < list.size(); i++ ){
            FileHeader fileHeader = list.get( i ) ;
            String fileName = fileHeader.getFileName();
            if( isMessyCode( fileName ) ){
                encoding = "UTF-8" ;
                break ;
            }
        }
        return encoding ;
    }

    private static boolean isMessyCode( String str ){
        for( int i = 0; i < str.length(); i++ ){
            char c = str.charAt( i ) ;
            // 当从Unicode编码向某个字符集转换时,如果在该字符集中没有对应的编码,则得到0x3f(即问号字符?)
            // 从其他字符集向Unicode编码转换时,如果这个二进制数在该字符集中没有标识任何的字符,则得到的结果是0xfffd
            if( (int)c == 0xfffd ){
                // 存在乱码
                return true ;
            }
        }
        return false ;
    }

    public static void zip(List<File> fileList, String dest, String passwd) {
         //创建目标文件
         ZipParameters par = new ZipParameters();
         par.setCompressionMethod(Zip4jConstants.COMP_DEFLATE);
         par.setCompressionLevel(Zip4jConstants.DEFLATE_LEVEL_NORMAL);

         if (passwd != null) {
             par.setEncryptFiles(true);
             par.setEncryptionMethod(Zip4jConstants.ENC_METHOD_STANDARD);
             par.setPassword(passwd.toCharArray());
         }

         ZipFile zipfile = null;
		try {
			zipfile = new ZipFile(dest);
	         for (File file : fileList) {
	             if (file.isDirectory()){
	                 zipfile.addFolder(file, par);
	             }
	             else{
	                 zipfile.addFile(file, par);
	             }
			}    
		} catch (ZipException e) {
			e.printStackTrace();
		}
    }


    
    public static void unZip( String zipPath, String destDir ) throws Exception {
        ZipFile zipFile = new ZipFile( zipPath ) ;
        zipFile.setFileNameCharset( getEncoding( zipPath ) ) ;
        zipFile.extractAll( destDir ) ;
    }
    
    public static void main(String[] args) throws Exception {
        try {
        	
        	List<File> list = new ArrayList<File>();
        	list.add(new File("D:\\logs\\log"));
        	list.add(new File("D:\\logs\\测试移动"));
        	list.add(new File("D:\\logs\\文件上传(支持拖动上传).zip"));
        	zip(list, "D:\\logs\\aa.zip", null);
        	
          //unZip("D:\\logs\\文件上传(支持拖动上传).zip", "D:\\logs/文件上传(支持拖动上传)"); 
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}


//以下是另一个压缩解压的工具类:
package com.explorer.utils;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
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 java.util.ArrayList;
import java.util.Enumeration;
import java.util.List;
import java.util.zip.ZipEntry;
import java.util.zip.ZipFile;
import java.util.zip.ZipInputStream;
import java.util.zip.ZipOutputStream;

import org.apache.commons.compress.archivers.zip.ZipArchiveEntry;
import org.apache.commons.compress.archivers.zip.ZipArchiveInputStream;
import org.apache.commons.compress.utils.IOUtils;
import org.apache.commons.io.FileUtils;
/**
 * 压缩(解压)文件工具类
 * @author Administrator
 *
 */
public class CompressUtils {
	private static final int  BUFFER_SIZE = 2 * 1024;
	
	  /**
	     *	 压缩成ZIP 方法1
	     * @param srcDir 压缩文件夹路径 
	     * @param out    压缩文件输出流
	     * @param KeepDirStructure  是否保留原来的目录结构,true:保留目录结构; 
	     *                          false:所有文件跑到压缩包根目录下(注意:不保留目录结构可能会出现同名文件,会压缩失败)
	     * @throws RuntimeException 压缩失败会抛出运行时异常 String srcDir
	     */
	    public static void toZip(List<File> fileList, OutputStream out, boolean KeepDirStructure) throws RuntimeException{   
	        long start = System.currentTimeMillis();
	        System.out.println("开始压缩...");
	        ZipOutputStream zos = null ;
	        try {
	            zos = new ZipOutputStream(out);
	            //File sourceFile = new File(srcDir);
	            //compress(sourceFile,zos,sourceFile.getName(),KeepDirStructure);
	            compress(fileList,zos,"",KeepDirStructure);
	            long end = System.currentTimeMillis();
	            System.out.println("压缩完成,耗时:" + (end - start) +" ms");
	        } catch (Exception e) {
	            throw new RuntimeException("zip error from ZipUtils",e);
	        }finally{
	            if(zos != null){
	                try {
	                    zos.close();
	                } catch (IOException e) {
	                    e.printStackTrace();
	                }
	            }
	        }
	    }

	    /**
	     * 压缩成ZIP 方法2
	     * @param srcFiles 需要压缩的文件列表
	     * @param out           压缩文件输出流
	     * @throws RuntimeException 压缩失败会抛出运行时异常
	     */

	    public static void toZip(List<File> srcFiles , OutputStream out)throws RuntimeException {

	        long start = System.currentTimeMillis();
	        ZipOutputStream zos = null ;
	        try {
	            zos = new ZipOutputStream(out);
	            for (File srcFile : srcFiles) {
	                byte[] buf = new byte[BUFFER_SIZE];
	                zos.putNextEntry(new ZipEntry(srcFile.getName()));
	                int len;
	                FileInputStream in = new FileInputStream(srcFile);
	                while ((len = in.read(buf)) != -1){
	                    zos.write(buf, 0, len);
	                }
	                zos.closeEntry();
	                in.close();
	            }
	            long end = System.currentTimeMillis();
	            System.out.println("压缩完成,耗时:" + (end - start) +" ms");
	        } catch (Exception e) {
	            throw new RuntimeException("zip error from ZipUtils",e);
	        }finally{
	            if(zos != null){
	                try {
	                    zos.close();
	                } catch (IOException e) {
	                    e.printStackTrace();
	                }
	            }
	        }
	    }

	    /** 递归压缩方法
	     * @param sourceFile 源文件
	     * @param zos        zip输出流
	     * @param name       压缩后的名称
	     * @param KeepDirStructure  是否保留原来的目录结构,true:保留目录结构; 
	     * false:所有文件跑到压缩包根目录下(注意:不保留目录结构可能会出现同名文件,会压缩失败)
	     * @throws Exception
	     */
	    private static void compress(List<File> fileList,ZipOutputStream zos, String name,
	            boolean KeepDirStructure) throws Exception {
	    	byte[] buf = new byte[BUFFER_SIZE];
	    	for (File file : fileList) {
	    		compress(file,zos,file.getName(),KeepDirStructure);
			}
	    }

	    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);
	            }
	            // Complete the entry
	            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);
	                    }
	                }
	            }
	        }
	    }
	
	    /**
	     * 解压zip文件(输入源zip路径,输出源zip路径)
	     */
	    public static void unzip(String zipDir, String descDir) {
	    	File zipFile = new File(zipDir);
	        try (ZipArchiveInputStream inputStream = getZipFile(zipFile)) {
	            File pathFile = new File(descDir);
	            if (!pathFile.exists()) {
	                pathFile.mkdirs();
	            }
	            ZipArchiveEntry entry = null;
	            while ((entry = inputStream.getNextZipEntry()) != null) {
	                if (entry.isDirectory()) {
	                    File directory = new File(descDir, entry.getName());
	                    directory.mkdirs();
	                } else {
	                    OutputStream os = null;
	                    try {
	                        os = new BufferedOutputStream(new FileOutputStream(new File(descDir, entry.getName())));
	                        //输出文件路径信息
	                        System.out.println("解压文件的当前路径为:" + descDir + entry.getName());
	                        IOUtils.copy(inputStream, os);
	                    } finally {
	                        IOUtils.closeQuietly(os);
	                    }
	                }
	            }
	            final File[] files = pathFile.listFiles();
	            if (files != null && files.length == 1 && files[0].isDirectory()) {
	                // 说明只有一个文件夹
	                FileUtils.copyDirectory(files[0], pathFile);
	                //免得删除错误, 删除的文件必须在/data/demand/目录下。
	                boolean isValid = files[0].getPath().contains("/data/www/");
	                if (isValid) {
	                    FileUtils.forceDelete(files[0]);
	                }
	            }
	            System.out.println("******************解压完毕********************");

	        } catch (Exception e) {
	        	e.printStackTrace();
	        }
	    }

	    private static ZipArchiveInputStream getZipFile(File zipFile) throws Exception {
	        return new ZipArchiveInputStream(new BufferedInputStream(new FileInputStream(zipFile)));
	    }
	 /**
     * @param args
     */
    static final int BUFFER = 2048;
    
    public static void unzip(String filename) {
        long startTime=System.currentTimeMillis();  
        System.out.println("开始解压...");
        try{
            int index1=filename.lastIndexOf(".");
            String zipName=filename.substring(0,index1);
            ZipFile zipFile = new ZipFile(filename);
            Enumeration enu = zipFile.entries();
            new File(zipName).mkdirs();
            while(enu.hasMoreElements()){
                ZipEntry zipEntry = (ZipEntry)enu.nextElement();
                if(zipEntry.isDirectory()){
                    new File(zipName+"/"+zipEntry.getName()).mkdirs();
                    continue;
                }
                BufferedInputStream bis = new BufferedInputStream(zipFile.getInputStream(zipEntry));
                File file = new File(zipName+"/"+zipEntry.getName());
                File parent = file.getParentFile();
                if(parent != null && !parent.exists()){
                    parent.mkdirs();
                }
                FileOutputStream fos = new FileOutputStream(file);
                BufferedOutputStream bos = new BufferedOutputStream(fos,BUFFER);
                byte[] array = new byte[BUFFER];
                while((bis.read(array, 0, BUFFER))!=-1){
                    bos.write(array, 0, BUFFER);
                }
                bos.flush();
                bos.close();
                bis.close();
            }
        }catch(Exception e){
            e.printStackTrace();
        }
        System.out.println("解压成功!");
        long endTime=System.currentTimeMillis();
        System.out.println("耗费时间: "+(endTime-startTime)+" ms"); 
    }
	    
	public static void main(String[] args) throws Exception {
	        /** 测试压缩方法1  */
	        //FileOutputStream fos1 = new FileOutputStream(new File("D:/mytest01.zip"));
	        //CompressUtils.toZip("D:/网站html模板", fos1,true);
	       
	        /** 测试压缩方法2  */
	        List<File> fileList = new ArrayList<>();
	        fileList.add(new File("D:/网站html模板"));
	        fileList.add(new File("D:/eclipse导入豆沙绿配置.txt"));
	        fileList.add(new File("D:/eclipse豆沙绿配置.epf"));
	        //FileOutputStream fos2 = new FileOutputStream(new File("D:/mytest02.zip"));
	        //CompressUtils.toZip(fileList, fos2,true);
	        
	        unzip("D:/SSR4.0扶墙1121.zip","D:/SSR4.0扶墙1121");
	}
	
}
			
		

 打赏        分享



评论