使用java基础类实现zip压缩和zip解压工具类分享

时间:2021-11-23 08:03:41 

使用java基础类写的一个简单的zip压缩解压工具类


package sun.net.helper;

import java.io.*;
import java.util.logging.Logger;
import java.util.zip.*;

public class ZipUtil {
    private final static Logger logger = Logger.getLogger(ZipUtil.class.getName());
    private static final int BUFFER = 1024*10;

    /**
     * 将指定目录压缩到和该目录同名的zip文件,自定义压缩路径
     * @param sourceFilePath  目标文件路径
     * @param zipFilePath     指定zip文件路径
     * @return
     */
    public static boolean zip(String sourceFilePath,String zipFilePath){
        boolean result=false;
        File source=new File(sourceFilePath);
        if(!source.exists()){
            logger.info(sourceFilePath+" doesn't exist.");
            return result;
        }
        if(!source.isDirectory()){
            logger.info(sourceFilePath+" is not a directory.");
            return result;
        }
        File zipFile=new File(zipFilePath+"/"+source.getName()+".zip");
        if(zipFile.exists()){
            logger.info(zipFile.getName()+" is already exist.");
            return result;
        }else{
            if(!zipFile.getParentFile().exists()){
                if(!zipFile.getParentFile().mkdirs()){
                    logger.info("cann't create file "+zipFile.getName());
                    return result;
                }
            }
        }
        logger.info("creating zip file...");
        FileOutputStream dest=null;
        ZipOutputStream out =null;
        try {
            dest = new FileOutputStream(zipFile);
            CheckedOutputStream checksum = new CheckedOutputStream(dest, new Adler32());
            out=new ZipOutputStream(new BufferedOutputStream(checksum));
            out.setMethod(ZipOutputStream.DEFLATED);
            compress(source,out,source.getName());
            result=true;
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }finally {
            if (out != null) {
                try {
                    out.closeEntry();
                } catch (IOException e) {
                    e.printStackTrace();
                }
                try {
                    out.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        if(result){
            logger.info("done.");
        }else{
            logger.info("fail.");
        }
        return result;
    }
    private static void compress(File file,ZipOutputStream out,String mainFileName) {
        if(file.isFile()){
            FileInputStream fi= null;
            BufferedInputStream origin=null;
            try {
                fi = new FileInputStream(file);
                origin=new BufferedInputStream(fi, BUFFER);
                int index=file.getAbsolutePath().indexOf(mainFileName);
                String entryName=file.getAbsolutePath().substring(index);
                System.out.println(entryName);
                ZipEntry entry = new ZipEntry(entryName);
                out.putNextEntry(entry);
                byte[] data = new byte[BUFFER];
                int count;
                while((count = origin.read(data, 0, BUFFER)) != -1) {
                    out.write(data, 0, count);
                }
            } catch (FileNotFoundException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }finally {
                if (origin != null) {
                    try {
                        origin.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }
        }else if (file.isDirectory()){
            File[] fs=file.listFiles();
            if(fs!=null&&fs.length>0){
                for(File f:fs){
                    compress(f,out,mainFileName);
                }
            }
        }
    }

    /**
     * 将zip文件解压到指定的目录,该zip文件必须是使用该类的zip方法压缩的文件
     * @param zipFile
     * @param destPath
     * @return
     */
    public static boolean unzip(File zipFile,String destPath){
        boolean result=false;
        if(!zipFile.exists()){
            logger.info(zipFile.getName()+" doesn't exist.");
            return result;
        }
        File target=new File(destPath);
        if(!target.exists()){
            if(!target.mkdirs()){
                logger.info("cann't create file "+target.getName());
                return result;
            }
        }
        String mainFileName=zipFile.getName().replace(".zip","");
        File targetFile=new File(destPath+"/"+mainFileName);
        if(targetFile.exists()){
            logger.info(targetFile.getName()+" already exist.");
            return result;
        }
        ZipInputStream zis =null;
        logger.info("start unzip file ...");
        try {
            FileInputStream fis= new FileInputStream(zipFile);
            CheckedInputStream checksum = new CheckedInputStream(fis, new Adler32());
            zis = new ZipInputStream(new BufferedInputStream(checksum));
            ZipEntry entry;
            while((entry = zis.getNextEntry()) != null) {
                int count;
                byte data[] = new byte[BUFFER];
                String entryName=entry.getName();
                int index=entryName.indexOf(mainFileName);
                String newEntryName=destPath+"/"+entryName.substring(index);
                System.out.println(newEntryName);
                File temp=new File(newEntryName).getParentFile();
                if(!temp.exists()){
                    if(!temp.mkdirs()){
                        throw new RuntimeException("create file "+temp.getName() +" fail");
                    }
                }
                FileOutputStream fos = new FileOutputStream(newEntryName);
                BufferedOutputStream dest = new BufferedOutputStream(fos,BUFFER);
                while ((count = zis.read(data, 0, BUFFER)) != -1) {
                    dest.write(data, 0, count);
                }
                dest.flush();
                dest.close();
            }
            result=true;
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            if (zis != null) {
                try {
                    zis.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        if(result){
            logger.info("done.");
        }else{
            logger.info("fail.");
        }
        return result;
    }
    public static void main(String[] args) throws IOException {
        //ZipUtil.zip("D:/apache-tomcat-7.0.30", "d:/temp");
        File zipFile=new File("D:/temp/apache-tomcat-7.0.30.zip");
        ZipUtil.unzip(zipFile,"d:/temp") ;
    }
}


另一个压缩解压示例,二个工具大家参考使用吧


package com.lanp;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.zip.ZipEntry;
import java.util.zip.ZipException;
import java.util.zip.ZipFile;
import java.util.zip.ZipInputStream;

/**
 * 解压ZIP压缩文件到指定的目录
 */
public final class ZipToFile {
 /**
  * 缓存区大小默认20480
  */
 private final static int FILE_BUFFER_SIZE = 20480;

 private ZipToFile() {

 }

 /**
  * 将指定目录的ZIP压缩文件解压到指定的目录
  * @param zipFilePath  ZIP压缩文件的路径
  * @param zipFileName  ZIP压缩文件名字
  * @param targetFileDir  ZIP压缩文件要解压到的目录
  * @return flag    布尔返回值
  */
 public static boolean unzip(String zipFilePath, String zipFileName, String targetFileDir){
  boolean flag = false;
  //1.判断压缩文件是否存在,以及里面的内容是否为空
  File file = null;   //压缩文件(带路径)
  ZipFile zipFile = null;
  file = new File(zipFilePath + "/" + zipFileName);
  System.out.println(">>>>>>解压文件【" + zipFilePath + "/" + zipFileName + "】到【" + targetFileDir + "】目录下<<<<<<");
  if(false == file.exists()) {
   System.out.println(">>>>>>压缩文件【" + zipFilePath + "/" + zipFileName + "】不存在<<<<<<");
   return false;
  } else if(0 == file.length()) {
   System.out.println(">>>>>>压缩文件【" + zipFilePath + "/" + zipFileName + "】大小为0不需要解压<<<<<<");
   return false;
  } else {
   //2.开始解压ZIP压缩文件的处理
   byte[] buf = new byte[FILE_BUFFER_SIZE];
   int readSize = -1;
   ZipInputStream zis = null;
   FileOutputStream fos = null;
   try {
    // 检查是否是zip文件
    zipFile = new ZipFile(file);
    zipFile.close();
    // 判断目标目录是否存在,不存在则创建
    File newdir = new File(targetFileDir);
    if (false == newdir.exists()) {
     newdir.mkdirs();
     newdir = null;
    }
    zis = new ZipInputStream(new FileInputStream(file));
    ZipEntry zipEntry = zis.getNextEntry();
    // 开始对压缩包内文件进行处理
    while (null != zipEntry) {
     String zipEntryName = zipEntry.getName().replace('\\', '/');
     //判断zipEntry是否为目录,如果是,则创建
     if(zipEntry.isDirectory()) {
      int indexNumber = zipEntryName.lastIndexOf('/');
      File entryDirs = new File(targetFileDir + "/" + zipEntryName.substring(0, indexNumber));
      entryDirs.mkdirs();
      entryDirs = null;
     } else {
      try {
       fos = new FileOutputStream(targetFileDir + "/" + zipEntryName);
       while ((readSize = zis.read(buf, 0, FILE_BUFFER_SIZE)) != -1) {
        fos.write(buf, 0, readSize);
       }
      } catch (Exception e) {
       e.printStackTrace();
       throw new RuntimeException(e.getCause());
      } finally {
       try {
        if (null != fos) {
         fos.close();
        }
       } catch (IOException e) {
        e.printStackTrace();
        throw new RuntimeException(e.getCause());
       }
      }
     }
     zipEntry = zis.getNextEntry();
    }
    flag = true;
   } catch (ZipException e) {
    e.printStackTrace();
    throw new RuntimeException(e.getCause());
   } catch (IOException e) {
    e.printStackTrace();
    throw new RuntimeException(e.getCause());
   } finally {
    try {
     if (null != zis) {
      zis.close();
     }
     if (null != fos) {
      fos.close();
     }
    } catch (IOException e) {
     e.printStackTrace();
     throw new RuntimeException(e.getCause());
    }
   }
  }
  return flag;
 }

 /**
  * 测试用的Main方法
  */
 public static void main(String[] args) {
  String zipFilePath = "C:\\home";
  String zipFileName = "lp20120301.zip";
  String targetFileDir = "C:\\home\\lp20120301";
  boolean flag = ZipToFile.unzip(zipFilePath, zipFileName, targetFileDir);
  if(flag) {
   System.out.println(">>>>>>解压成功<<<<<<");
  } else {
   System.out.println(">>>>>>解压失败<<<<<<");
  }
 }

}

标签:java,zip,压缩,解压
0
投稿

猜你喜欢

  • java程序设计语言的优势及特点

    2022-08-16 09:12:57
  • C#移除字符串中的不可见Unicode字符 案例代码

    2023-04-28 19:06:06
  • android自定义view之模拟qq消息拖拽删除效果

    2023-01-29 11:48:34
  • Android向node.js编写的服务器发送数据并接收请求

    2022-10-12 02:08:21
  • Java实现人机猜拳游戏

    2023-10-16 08:47:56
  • Android开发技巧之在a标签或TextView控件中单击链接弹出Activity(自定义动作)

    2023-12-26 09:11:39
  • 最简单的MyBatis Plus的多表联接、分页查询实现方法

    2022-07-10 05:21:49
  • java设置session过期时间的实现方法

    2022-02-18 20:25:29
  • java swing 创建一个简单的QQ界面教程

    2022-09-08 06:51:39
  • Opencv实现读取摄像头和视频数据

    2023-07-16 15:19:58
  • Springboot-注解-操作日志的实现方式

    2023-10-10 13:54:35
  • c++如何实现跳表(skiplist)

    2022-02-10 18:05:58
  • 超实用的Java快捷键(总结)

    2022-04-06 20:56:51
  • C#制作鹰眼的详细全过程(带注释)实例代码

    2022-03-01 06:56:12
  • Android简单实现圆盘抽奖界面

    2022-07-25 08:35:27
  • Spring Boot示例代码整合Redis详解

    2022-03-20 19:23:37
  • java实现钉钉机器人消息推送的示例代码

    2023-05-18 13:53:25
  • Java中缀表达式转后缀表达式实现方法详解

    2021-08-25 02:57:20
  • Android编程创建桌面快捷方式的常用方法小结【2种方法】

    2023-12-07 00:50:35
  • java编译器和JVM的区别

    2023-07-18 20:34:48
  • asp之家 软件编程 m.aspxhome.com