[Java基础]-- java压缩文件和解压文件

一、需要的包

commons-compress-1.9.jar包,下载地址:https://commons.apache.org/proper/commons-compress/download_compress.cgi

二、java实现压缩文件和解压文件的工具类

ZipFileUtil.java

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;

import org.apache.commons.compress.archivers.ArchiveEntry;
import org.apache.commons.compress.archivers.zip.Zip64Mode;
import org.apache.commons.compress.archivers.zip.ZipArchiveEntry;
import org.apache.commons.compress.archivers.zip.ZipArchiveInputStream;
import org.apache.commons.compress.archivers.zip.ZipArchiveOutputStream;
 /**
  * 
  *@类功能说明:压缩文件和解压文件的工具类
  *@修改人员名: yang
  *@修改日期:    2016-1-3 下午03:07:59
  *@创建时间:    2016-1-3 下午03:07:59
  *@版本:V1.0
  * ------------------------------------------
  *  修改次数                 修改人员            修改内容                  修改原因                     
  *  
  * @备注:可以直接使用
  */
public class ZipFileUtil {
     
    /**
     * @功能:                        将多个文件文件压缩成zip格式
     * @param files               需要压缩的文件
     * @param zipFilePath  压缩后的zip文件路径   ,如"F:\\hh.zip";
     */
    public static void compressFilesZip(File[] files,String zipFilePath) {
        if(files != null && files.length >0) {
            if(isEndsWithZip(zipFilePath)) {
                ZipArchiveOutputStream zaos = null;
                try {
                    File zipFile = new File(zipFilePath);
                    zaos = new ZipArchiveOutputStream(zipFile);
                    //Use Zip64 extensions for all entries where they are required
                    zaos.setUseZip64(Zip64Mode.AsNeeded);
                    //将每个文件用ZipArchiveEntry封装
                    //再用ZipArchiveOutputStream写到压缩文件中
                    for(File file : files) {
                        if(file != null) {
                            ZipArchiveEntry zipArchiveEntry  = new ZipArchiveEntry(file,file.getName());
                            zaos.putArchiveEntry(zipArchiveEntry);
                            InputStream is = null;
                            try {
                                is = new BufferedInputStream(new FileInputStream(file));
                                byte[] buffer = new byte[1024 * 5]; 
                                int len = -1;
                                while((len = is.read(buffer)) != -1) {
                                    //把缓冲区的字节写入到ZipArchiveEntry
                                    zaos.write(buffer, 0, len);
                                }
                                //Writes all necessary data for this entry.
                                zaos.closeArchiveEntry(); 
                            }catch(Exception e) {
                                throw new RuntimeException(e);
                            }finally {
                                if(is != null)
                                    is.close();
                            }
                        }
                    }
                    zaos.finish();
                }catch(Exception e){
                    throw new RuntimeException(e);
                }finally {
                        try {
                            if(zaos != null) {
                                zaos.close();
                            }
                        } catch (Exception e) {
                            throw new RuntimeException(e);
                        }
                }
            }
        }
    }
    /**
     *@功能:                             把zip压缩文件解压到指定的文件夹下
     * @param zipFilePath   zip文件路径, 如 "F:\\hh.zip"
     * @param saveFileDir   解压后的文件存放路径, 如"F:/myhh/"
     */
    public static void decompressZip(String zipFilePath,String saveFileDir) {
    if(!saveFileDir.endsWith("\\") && !saveFileDir.endsWith("/") ){  
             saveFileDir += File.separator;  
         }  
         File dir = new File(saveFileDir);  
         //判断是否存在该目录
         if(!dir.exists()){  
             dir.mkdirs();  
         }  
         File file = new File(zipFilePath);  
         //判断是否存在该文件
         if (file.exists()) {  
             InputStream is = null;   
             ZipArchiveInputStream zas = null;  
             try {  
                 is = new FileInputStream(file);  
                 zas = new ZipArchiveInputStream(is);  
                 ArchiveEntry archiveEntry = null;
                 //遍历获取文件名称
                 while ((archiveEntry = zas.getNextEntry()) != null) {   
                     // 获取压缩文件中的名称
                     String entryFileName = archiveEntry.getName();  
                     //解压后的文件存放路径
                     String entryFilePath = saveFileDir + entryFileName;  
                     OutputStream os = null;  
                     try {  
                         // 将解压出的文件写到指定路径  
                         File entryFile = new File(entryFilePath);  
                         if(entryFileName.endsWith("/")){  
                             entryFile.mkdirs();  
                         }else{  
                             os = new BufferedOutputStream(new FileOutputStream(entryFile));                              
                             byte[] buffer = new byte[1024 ];   
                             int len = -1;   
                             while((len = zas.read(buffer)) != -1) {  
                                 os.write(buffer, 0, len);   
                             }  
                         }  
                     } catch (IOException e) {  
                         throw new IOException(e);  
                     } finally {  
                         if (os != null) {  
                             os.flush();  
                             os.close();  
                         }  
                     }  
                 }   
             } catch (Exception e) {  
                 throw new RuntimeException(e);  
             } finally {  
                 try {  
                     if (zas != null) {  
                         zas.close();  
                     }  
                     if (is != null) {  
                    is.close();  
                     }  
                 } catch (Exception e) {  
                     throw new RuntimeException(e);  
                 }  
             }  
         }  
    }
    /**
     * @功能:                          判断文件名是否以.zip为后缀
     * @param fileName        需要判断的文件名
     * @return                           如果是zip文件返回true,否则返回false
     */
    public static boolean isEndsWithZip(String fileName) {
    boolean flag = false;
    if(fileName != null && !"".equals(fileName.trim())) {
    if(fileName.endsWith(".ZIP")||fileName.endsWith(".zip")){
    flag = true;
    }
    }
    return flag;
    }
}

三、测试类

//测试压缩多个文件成一个文件

@Test
public void testZip(){

       //需要压缩的文件路径
File files[]=new File("F:\\zip").listFiles();
try{
ZipFileUtil.compressFiles2Zip(files, "F:\\hh.zip");//F:\\hh.zip是压缩后的文件路径
}catch(Exception e){
e.printStackTrace();
}
}

//解压zip文件
@Test
public void testComparess(){
try{
String path="F:\\hh.zip";
ZipFileUtil.decompressZip(path, "F:\\myhh\\");
}catch(Exception e){
e.printStackTrace();
}

四、测试通过,可以直接正常使用

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

往事随风ing

你的鼓励将是我创作的最大动力!

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值