在Java中通过压缩流与解压缩流实现文件以及文件夹的压缩与解压缩


前言

在计算机编程中,文件的压缩和解压缩是一项常见的任务。它不仅可以节省存储空间,还可以提高文件传输的效率。Java作为一种广泛使用的编程语言,提供了丰富的API来处理这种任务。在这篇文章中,我们将探讨如何在Java中使用压缩流和解压缩流来实现文件和文件夹的压缩与解压缩。


一、压缩包的解压缩

解压的本质:把压缩包里面的每一个文件或者文件夹读取出来,按照层级拷贝到目的地中。

1、步骤

(1)、引入库

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

(2)、创建File表示要解压的压缩包以及解压到的目标位置

 File src = new File("D:\\aaa.zip");
 File dest = new File("D:\\");

(3)、定义一个方法用来解压缩

1、创建一个解压缩流用来读取压缩包中的数据,获取到压缩包里面的每一个zipentry对象,如果获取到文件或者文件夹,解压缩流获取的结果就不是null,否则为null。

 public static void unzip(File src, File dest) throws IOException {
        //创建一个解压缩流用来读取压缩包中的数据
        ZipInputStream zip = new ZipInputStream(new FileInputStream(src));
        //要获取到压缩包里面的每一个zipentry对象
        //表示当前在压缩包中获取的文件或者文件夹
        ZipEntry entry;
        while ((entry = zip.getNextEntry()) != null){}

2.如果entry不是null,则判断是否为文件夹,如果是文件夹,则需要在目的地创建一个同样的文件夹,如果是文件,则需要读取压缩包中的文件,并把他存到目的地文件夹中(按照层级目录存放)。
注意:在每次文件处理完毕后,需要调用一次压缩流中的closeEntry()方法。

while ((entry = zip.getNextEntry()) != null){
            if(entry.isDirectory()){
                //文件夹:需要在目的地dest处创建一个同样的文件夹
                File file = new File(dest,entry.toString());
                file.mkdirs();
            }else {
                //文件:需要读取压缩包中的文件,并把他存到目的地dest文件夹中(按照层级目录存放)
                FileOutputStream fos = new FileOutputStream(new File(dest,entry.toString()));
                int b;
                while ((b = zip.read()) != -1){
                    //写到目的地
                    fos.write(b);
                }
                fos.close();
                //表示压缩包中的一个文件处理完毕
                zip.closeEntry();
            }
        }
        zip.close();

2、完整代码

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

public class Demo1 {
    public static void main(String[] args) throws IOException {
        //1.创建一个File表示要解压的压缩包
        File src = new File("D:\\aaa.zip");
        //2.创建一个File表示压缩的目的地
        File dest = new File("D:\\");

        //调用方法
        unzip(src,dest);
    }

    //定义一个方法用来解压
    public static void unzip(File src, File dest) throws IOException {
        //解压的本质:把压缩包里面的每一个文件或者文件夹读取出来,按照层级拷贝到目的地中

        //创建一个解压缩流用来读取压缩包中的数据
        ZipInputStream zip = new ZipInputStream(new FileInputStream(src));
        //要获取到压缩包里面的每一个zipentry对象
        //表示当前在压缩包中获取的文件或者文件夹
        ZipEntry entry;
        while ((entry = zip.getNextEntry()) != null){
            if(entry.isDirectory()){
                //文件夹:需要在目的地dest处创建一个同样的文件夹
                File file = new File(dest,entry.toString());
                file.mkdirs();
            }else {
                //文件:需要读取压缩包中的文件,并把他存到目的地dest文件夹中(按照层级目录存放)
                FileOutputStream fos = new FileOutputStream(new File(dest,entry.toString()));
                int b;
                while ((b = zip.read()) != -1){
                    //写到目的地
                    fos.write(b);
                }
                fos.close();
                //表示压缩包中的一个文件处理完毕
                zip.closeEntry();
            }
        }
        zip.close();
    }
}

二、文件的压缩

1.步骤

(1)、引入库

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.ZipOutputStream;

(2)、创建File对象表示要压缩的文件和压缩包的位置

        File src = new File("D:\\a.txt");
        File dest = new File("D:\\");

(3)、定义一个方法用来文件压缩

1、创建压缩流关联压缩包,创建ZipEntry对象,表示压缩包里面的文件,然后把ZipEntry对象放到压缩包当中,到这里相当于已经把压缩包中的框架搭好了

 //1.创建压缩流关联压缩包
        ZipOutputStream zos = new ZipOutputStream(new FileOutputStream(new File(dest,"a.zip")));
        //2.创建ZipEntry对象,表示压缩包里面的每一个文件和文件夹
        //压缩包里面的路径
        ZipEntry entry = new ZipEntry("a.text");
        //3.把ZipEntry对象放到压缩包当中
        zos.putNextEntry(entry);

2.把文件中的数据写到压缩包中

 //4.把src文件中的数据写到压缩包中
        FileInputStream fis  = new FileInputStream(src);
        int b;
        while ((b = fis.read()) != -1){
            zos.write(b);
        }

2、完整代码

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.ZipOutputStream;

public class Demo2 {
    public static void main(String[] args) throws IOException {
        //压缩单个文件

        //1.创建File对象表示要压缩的文件
        File src = new File("D:\\a.txt");
        //2.创建File对象表示压缩包的位置
        File dest = new File("D:\\");
        //3.调用方法进行压缩
        toZip(src,dest);
    }
    private static void toZip(File src, File dest) throws IOException {
        //1.创建压缩流关联压缩包
        ZipOutputStream zos = new ZipOutputStream(new FileOutputStream(new File(dest,"a.zip")));
        //2.创建ZipEntry对象,表示压缩包里面的每一个文件和文件夹
        //压缩包里面的路径
        ZipEntry entry = new ZipEntry("a.text");
        //3.把ZipEntry对象放到压缩包当中
        zos.putNextEntry(entry);
        //4.把src文件中的数据写到压缩包中
        FileInputStream fis  = new FileInputStream(src);
        int b;
        while ((b = fis.read()) != -1){
            zos.write(b);
        }
        zos.closeEntry();
        zos.close();
    }
}

二、文件夹的压缩

1.步骤

(1)、引入库

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.ZipOutputStream;

(2)、创建File对象表示要压缩的文件夹和压缩包的位置

//1.创建File对象表示要压缩的文件夹
        File src = new File("D:\\aaa");
        //2.创建File对象表示压缩包放在哪里(压缩包的父级路径)
        File destParent = src.getParentFile();
        //3.创建压缩流关联压缩包的路径
        File dest = new File(destParent,src.getName() + ".zip");

(3)、创建压缩流关联压缩包

ZipOutputStream zos = new ZipOutputStream(new FileOutputStream(dest));

(4)、定义一个方法用来文件夹压缩

作用:获取src里面的每一个文件,变成ZipEntry对象,放入到压缩包当中
参数一:数据源
参数二:压缩流
参数三:压缩包内部的路径

 private static void toZip(File src, ZipOutputStream zos, String name)

1、进入src文件夹,遍历数组

 //1.进入src文件夹
        File[] files = src.listFiles();
        //2.遍历数组
        for (File file : files) {}

2、判断数组中的每一个元素,如果为文件,变成ZipEntry对象,放入到压缩包当中(这里相当于搭框架),同时读取文件中的数据,写到压缩包(这里为填充数据),如果是文件夹,则继续递归。
注意: ZipEntry entry = new ZipEntry() 代表的是在压缩包内部的路径

for (File file : files) {
            if(file.isFile()){
                //3.判断为文件,变成ZipEntry对象,放入到压缩包当中
                ZipEntry entry = new ZipEntry(name + "\\" + file.getName());
                zos.putNextEntry(entry);
                //读取文件中的数据,写到压缩包
                FileInputStream fis = new FileInputStream(file);
                int b;
                while ((b = fis.read()) != -1){
                    zos.write(b);
                }
                fis.close();
                zos.closeEntry();
            }else {
                //4.判断为文件夹,递归
                toZip(file,zos,name+"\\"+file.getName());
            }
        }

2、完整代码

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.ZipOutputStream;


public class Demo3 {
    public static void main(String[] args) throws IOException {
        //压缩文件夹
        //1.创建File对象表示要压缩的文件夹
        File src = new File("D:\\aaa");
        //2.创建File对象表示压缩包放在哪里(压缩包的父级路径)
        File destParent = src.getParentFile();
        //3.创建压缩流关联压缩包的路径
        File dest = new File(destParent,src.getName() + ".zip");
        //4.创建压缩流关联压缩包
        ZipOutputStream zos = new ZipOutputStream(new FileOutputStream(dest));
        //5.获取src里面的每一个文件,变成ZipEntry对象,放入压缩包当中
        toZip(src,zos,src.getName());//aaa
        //6.释放资源
        zos.close();
    }
    /*
    * 作用:获取src里面的每一个文件,变成ZipEntry对象,放入到压缩包当中
    * 参数一:数据源
    * 参数二:压缩流
    * 参数三:压缩包内部的路径
    * */
    private static void toZip(File src, ZipOutputStream zos, String name) throws IOException {
        //1.进入src文件夹
        File[] files = src.listFiles();
        //2.遍历数组
        for (File file : files) {
            if(file.isFile()){
                //3.判断为文件,变成ZipEntry对象,放入到压缩包当中
                ZipEntry entry = new ZipEntry(name + "\\" + file.getName());
                zos.putNextEntry(entry);
                //读取文件中的数据,写到压缩包
                FileInputStream fis = new FileInputStream(file);
                int b;
                while ((b = fis.read()) != -1){
                    zos.write(b);
                }
                fis.close();
                zos.closeEntry();
            }else {
                //4.判断为文件夹,递归
                toZip(file,zos,name+"\\"+file.getName());
            }
        }
    }
}

总结

总的来说,压缩与解压缩的大致思想相似,都是对目标文件进行遍历然后判断,压缩主要是先搭建好框架再进行数据的填充,解压缩与文件夹拷贝思路类似。

  • 29
    点赞
  • 27
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
Java自带的解压缩库并不支持RAR格式,需要借助第三方库来完成解压缩操作。这里介绍使用commons-compress库来解压缩RAR文件,并且设置文件夹的字符编码为gbk。 首先需要添加commons-compress的依赖: ```xml <dependency> <groupId>org.apache.commons</groupId> <artifactId>commons-compress</artifactId> <version>1.21</version> </dependency> ``` 然后可以使用以下代码来解压缩RAR文件: ```java import org.apache.commons.compress.archivers.ArchiveEntry; import org.apache.commons.compress.archivers.ArchiveInputStream; import org.apache.commons.compress.archivers.ArchiveStreamFactory; import org.apache.commons.compress.archivers.rar.RarArchiveInputStream; import org.apache.commons.compress.utils.IOUtils; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.nio.charset.Charset; public class RarExtractor { public static void extract(String inputFilePath, String outputDirPath) throws Exception { File inputFile = new File(inputFilePath); File outputDir = new File(outputDirPath); if (!outputDir.exists()) { outputDir.mkdirs(); } try (ArchiveInputStream ais = new ArchiveStreamFactory() .createArchiveInputStream(ArchiveStreamFactory.RAR, new FileInputStream(inputFile), Charset.forName("ISO-8859-1"))) { RarArchiveInputStream rai = (RarArchiveInputStream) ais; ArchiveEntry entry; while ((entry = rai.getNextEntry()) != null) { if (!rai.canReadEntryData(entry)) { continue; } String fileName = entry.getName(); File outputFile = new File(outputDir, fileName); if (entry.isDirectory()) { outputFile.mkdirs(); } else { File parentFile = outputFile.getParentFile(); if (!parentFile.exists()) { parentFile.mkdirs(); } try (FileOutputStream fos = new FileOutputStream(outputFile)) { IOUtils.copy(rai, fos); } } } } } } ``` 在调用extract方法时,需要传入要解压缩的RAR文件路径和输出目录路径。解压缩过程,使用ISO-8859-1字符集来读取RAR文件文件名和目录名,然后在输出文件时使用gbk字符集来设置文件夹的字符编码。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

窒息的鱼c

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

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

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

打赏作者

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

抵扣说明:

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

余额充值