Java如何实现压缩文件与解压缩zip文件

 更新时间:2022年12月12日 09:27:30   作者:yujkss  
这篇文章主要介绍了Java如何实现压缩文件与解压缩zip文件问题,具有很好的参考价值,希望对大家有所帮助。如有错误或未考虑完全的地方,望不吝赐教

Java压缩文件与解压缩zip文件

在日常的使用中经常会使用到像WinRAR或WinZIP这样的压缩文件,通过这些软件可以把一个很大的文件进行压缩以方便传输。

在JAVA中 为了减少传输时的数据量也提供了专门的压缩流,可以将文件或文件夹压缩成ZIP、JAR、GZIP等文件的格式。

ZIP是一种较为常见的压缩形式,在Java中要想实现ZIP的压缩需要导入java.util.zip包,可以使用此包中的ZipFile、ZipOutputStream、ZipInputStream、ZipEntry几个类完成。

testZip

package com.kuang.zip;

import org.apache.commons.io.IOUtils;

import java.io.*;
import java.util.Enumeration;
import java.util.zip.ZipEntry;
import java.util.zip.ZipFile;

public class testZip {


    public static void unZipIt(String file, String outputFolder) throws IOException {

        ZipFile zipFile = null;
        InputStream in=null;
        OutputStream out=null;
        try {
            zipFile = new ZipFile(file);
            Enumeration <? extends ZipEntry>  entries = zipFile.entries();
            while (entries.hasMoreElements()) {
                ZipEntry entry = entries.nextElement();
                File entryDestination = new File(outputFolder, entry.getName());
                if (entry.isDirectory()) {
                    entryDestination.mkdirs();
                } else {
                    entryDestination.getParentFile().mkdirs();
                    try {
                        out = new FileOutputStream(entryDestination);
                        in = zipFile.getInputStream(entry);
                        IOUtils.copy(in, out);
                    } catch (IOException e) {
                        throw e;
                    }finally {
                        IOUtils.closeQuietly(in);
                        IOUtils.closeQuietly(out);
                    }
                }
            }
        } finally {
            try {
                if(zipFile!=null){zipFile.close();zipFile=null;}
            } catch (IOException e) {
            }
        }
    }

    public static void main(String[] args) throws Exception {

        unZipIt("D:\\Test\\TestbyYTT.zip","D:\\Test\\");

    }

}

org.apache.commons.io.IOUtils需引入maven依赖

<!-- https://mvnrepository.com/artifact/commons-io/commons-io -->
<dependency>
    <groupId>commons-io</groupId>
    <artifactId>commons-io</artifactId>
    <version>2.4</version>
</dependency>

org.apache.commons.io.IOUtils.closeQuietly()只是确保流会被关闭,无论流是否正常结束,看源码发现closeQuietly它会忽略异常


那么为什么IOUtils.closeQuietly()会在2.6的时候将它标记为过时呢?

因为Java7里的try-with-resource语法糖的出现,之前定义在try catch外部的流移到了try后边的括号里,不再需要手动关闭了,它会自行处理。

public static void readAll() {
    try (
        FileReader fileReader = new FileReader("test");
        BufferedReader bufferedReader = new BufferedReader(fileReader)
    ) {
        String line;

        while ((line = bufferedReader.readLine()) != null) {
            System.out.println(line);
        }
    } catch (IOException e) {
        e.printStackTrace();
    }
}

拓展:还有一种语法叫multi-catch 可以简化多个catch

FileZip

package com.kuang.zip;

import java.io.*;
import java.util.zip.*;
import java.util.zip.ZipEntry;


public class FileZip {
    /**
     * zip文件压缩
     * @param inputFile 待压缩文件夹/文件名
     * @param outputFile 生成的压缩包名字
     */

    public static void ZipCompress(String inputFile, String outputFile) throws Exception {
        //创建zip输出流
        ZipOutputStream out = new ZipOutputStream(new FileOutputStream(outputFile));
        //创建缓冲输出流
        BufferedOutputStream bos = new BufferedOutputStream(out);
        File input = new File(inputFile);
        compress(out, bos, input,null);
        bos.close();
        out.close();
    }
    /**
     * @param name 压缩文件名,可以写为null保持默认
     */
    //递归压缩
    public static void compress(ZipOutputStream out, BufferedOutputStream bos, File input, String name) throws IOException {
        if (name == null) {
            name = input.getName();
        }
        //如果路径为目录(文件夹)
        if (input.isDirectory()) {
            //取出文件夹中的文件(或子文件夹)
            File[] flist = input.listFiles();

            if (flist.length == 0)//如果文件夹为空,则只需在目的地zip文件中写入一个目录进入
            {
                out.putNextEntry(new ZipEntry(name + "/"));
            } else//如果文件夹不为空,则递归调用compress,文件夹中的每一个文件(或文件夹)进行压缩
            {
                for (int i = 0; i < flist.length; i++) {
                    compress(out, bos, flist[i], name + "/" + flist[i].getName());
                }
            }
        } else//如果不是目录(文件夹),即为文件,则先写入目录进入点,之后将文件写入zip文件中
        {
            out.putNextEntry(new ZipEntry(name));
            FileInputStream fos = new FileInputStream(input);
            BufferedInputStream bis = new BufferedInputStream(fos);
            int len=-1;
            //将源文件写入到zip文件中
            byte[] buf = new byte[1024];
            while ((len = bis.read(buf)) != -1) {
                bos.write(buf,0,len);
            }
            bis.close();
            fos.close();
        }
    }

    /**
     * zip解压
     * @param inputFile 待解压文件名
     * @param destDirPath  解压路径
     */

    public static void ZipUncompress(String inputFile,String destDirPath) throws Exception {
        File srcFile = new File(inputFile);//获取当前压缩文件
        // 判断源文件是否存在
        if (!srcFile.exists()) {
            throw new Exception(srcFile.getPath() + "所指文件不存在");
        }
        //开始解压
        //构建解压输入流
        ZipInputStream zIn = new ZipInputStream(new FileInputStream(srcFile));
        ZipEntry entry = null;
        File file = null;
        while ((entry = zIn.getNextEntry()) != null) {
            if (!entry.isDirectory()) {
                file = new File(destDirPath, entry.getName());
                if (!file.exists()) {
                    new File(file.getParent()).mkdirs();//创建此文件的上级目录
                }
                OutputStream out = new FileOutputStream(file);
                BufferedOutputStream bos = new BufferedOutputStream(out);
                int len = -1;
                byte[] buf = new byte[1024];
                while ((len = zIn.read(buf)) != -1) {
                    bos.write(buf, 0, len);
                }
                // 关流顺序,先打开的后关闭
                bos.close();
                out.close();
            }
        }
    }


    public static void main(String[] args) {
        try {

            ZipCompress("D:\\Test", "D:\\Test\\TestbyYTT.zip");
            ZipUncompress("D:\\Test\\TestbyYTT.zip","D:\\Test\\TestbyYTT的解压文件");
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

总结

以上为个人经验,希望能给大家一个参考,也希望大家多多支持脚本之家。

相关文章

  • IDEA2020如何打开Run Dashboard的方法步骤

    IDEA2020如何打开Run Dashboard的方法步骤

    这篇文章主要介绍了IDEA2020如何打开Run Dashboard的方法步骤,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧
    2020-07-07
  • 详解MyBatisPlus如何实现分页和查询操作

    详解MyBatisPlus如何实现分页和查询操作

    这篇文章主要为大家详细介绍了MyBatisPlus是如何实现分页和查询操作的,文中的示例代码讲解详细,对我们学习有一定的帮助,需要的可以参考一下
    2022-05-05
  • Java HashSet添加 遍历元素源码分析

    Java HashSet添加 遍历元素源码分析

    这篇文章主要为大家详细介绍了HashSet、HashMap底层添加、遍历元素的机制,追踪并分析源码,文中的示例代码讲解详细,希望对大学有所帮助
    2022-07-07
  • Java基于字符界面的简易收银台

    Java基于字符界面的简易收银台

    这篇文章主要为大家详细介绍了Java基于字符界面的简易收银台,文中示例代码介绍的非常详细,具有一定的参考价值,感兴趣的小伙伴们可以参考一下
    2021-06-06
  • 详解hashCode()和equals()的本质区别和联系

    详解hashCode()和equals()的本质区别和联系

    这篇文章主要介绍了详解hashCode()和equals()的本质区别和联系,本文先对两种方法作了介绍,然后对二者联系进行分析,具有一定参考价值,需要的朋友可以了解下。
    2017-09-09
  • Java中ArrayList初始化的四种方法详解

    Java中ArrayList初始化的四种方法详解

    这篇文章主要介绍了Java中ArrayList初始化的四种方法,本文给大家介绍的非常详细,对大家的学习或工作具有一定的参考借鉴价值,需要的朋友可以参考下
    2021-04-04
  • classpath和classpath*的区别详解

    classpath和classpath*的区别详解

    这篇文章主要为大家介绍了classpath和classpath*的区别详解,有需要的朋友可以借鉴参考下,希望能够有所帮助,祝大家多多进步,早日升职加薪
    2023-10-10
  • java面试常见问题之Hibernate总结

    java面试常见问题之Hibernate总结

    这篇文章主要介绍了在java面试过程中hibernate比较常见的问题,包括Hibernate的检索方式,Hibernate中对象的状态,Hibernate的3种检索策略是什么,Session的find()方法以及Query接口的区别等方面问题的总结,需要的朋友可以参考下
    2015-07-07
  • 详解在spring boot中消息推送系统设计与实现

    详解在spring boot中消息推送系统设计与实现

    这篇文章主要介绍了详解在spring boot中消息推送系统设计与实现,小编觉得挺不错的,现在分享给大家,也给大家做个参考。一起跟随小编过来看看吧
    2019-05-05
  • Java 位图法排序的使用方法

    Java 位图法排序的使用方法

    本篇文章,小编将为大家介绍关于Java 位图法排序的使用方法,有需要的朋友可以参考一下
    2013-04-04

最新评论