Java如何实现压缩文件与解压缩zip文件
作者:yujkss 发布时间:2022-01-28 09:14:00
标签: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();
}
}
}
来源:https://blog.csdn.net/qq_39900031/article/details/124028853


猜你喜欢
- 一:什么是协变与逆变协变指能够使用比原始指定的派生类型的派生程度更大(更具体的)的类型,逆变指能够使用比原始指定的派生类型的派生程度更小(不
- 1. json数据类型类型描述Number数字型String字符串型Boolean布尔型Array数组Object对象null空值(1)js
- 1.介绍在SpringBoot的Web项目中,默认采用的是内置Tomcat,当然也可以配置支持内置的jetty,内置有什么好处呢? 1. 方
- 01: 异步任务02: 定时任务一、SpringBoot--任务:邮件任务1.1 添加依赖(增加邮件支持)pom.xml <depen
- 1、添加spring相关jar包2、配置ehcache jar包。3、添加ehcache mybatis 适配器jar包(在mybatis官
- using System; using System.Collections.Generic; using
- 前言RabbitMQ 是使用 Erlang 语言开发的消息中间件, 其遵循了高级消息队列协议(Advanced Message Queuin
- 先给大家展示下效果图:不知道大家对效果图感觉怎么样,个人觉还不错,感兴趣的朋友可以参考下实现代码哦。public class ToggleB
- 废话不多说,先看效果,如果大家感觉不错,请参考实现代码这个功能我是用Fragmentdialog里面做的,也遇到不少坑第一,就是设置背景的d
- OpenCV概述OpenCV做为功能强大的计算机视觉开源框架,包含了500多个算法实现,而且还在不断增加,其最新版本已经更新到3.2。其SD
- 如今,手机应用渗透到各行各业,数量难以计数,其中大多数应用都会使用到网络,与服务器的交互势不可挡,那么android当中访问网络有哪些方式呢
- 本文实例讲述了Android实现便于批量操作可多选的图片ListView。分享给大家供大家参考,具体如下:之前项目需要实现一个可多选的图片列
- 先看下利用wheelview实现滚动随机选择号码效果:直接上代码 首页就是dialog显示不在描述 主要看dialog代码package c
- 基于Java的简单的用户管理系统,供大家参考,具体内容如下此系统功能和方法都比较简单本次系统通过控制台输入商品的基本信息,加入管理员的登录与
- 本文实例讲述了Android编程实现的手写板和涂鸦功能。分享给大家供大家参考,具体如下:下面仿一个Android手写板和涂鸦的功能,直接上代
- 本文实例讲述了Android编程开发中ListView的常见用法。分享给大家供大家参考,具体如下:一、ListView的使用步骤ListVi
- 1. 启用AOPa. 在类上添加@Aspect注解b. 注入该类, 可以使用@Component进行注入到Spring容器中2. 通过Poi
- 问题在本地启动dubbo时,服务注册在本地的zookeeper ,但是注册IP却不是本地的iP。产生问题,导致consumer 找不到pro
- 单一职责原则:一个类,只有一个引起它变化的原因。为什么需要单一职责原则?如果一个类有多个原因要去修改它,那么修改一个功能时,可能会让其他功能
- 下面给大家分享一小段代码给大家介绍C# 输出字符串到文本文件中,具体代码如下所示: public class WriteHelp