Java如何实现压缩文件与解压缩zip文件
作者:yujkss 时间:2022-01-28 09:14:00
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
标签:Java,压缩文件,解压缩,zip文件
![](/images/zang.png)
![](/images/jiucuo.png)
猜你喜欢
解决mybatis批量更新出现SQL报错问题
2023-11-29 04:12:47
![](https://img.aspxhome.com/file/2023/5/60155_0s.png)
Java ForkJoin框架的原理及用法
2022-03-13 05:26:51
![](https://img.aspxhome.com/file/2023/5/60935_0s.png)
java中使用数组进行模拟加密的方法
2023-11-18 15:37:39
Java的类型擦除式泛型详解
2022-01-02 11:59:00
![](https://img.aspxhome.com/file/2023/8/61608_0s.jpg)
SpringBoot配置文件中密码属性加密的实现
2022-07-08 18:32:03
![](https://img.aspxhome.com/file/2023/8/64018_0s.jpg)
Lombok为啥这么牛逼?SpringBoot和IDEA官方都要支持它
2021-10-18 23:04:50
![](https://img.aspxhome.com/file/2023/7/64497_0s.png)
Spring源码解析之BeanPostProcessor知识总结
2022-04-07 22:13:34
![](https://img.aspxhome.com/file/2023/3/65173_0s.jpg)
为什么rest接口返回json建议采用下划线形式,不要用驼峰
2023-06-24 23:23:16
Java线程池ThreadPoolExecutor源码深入分析
2023-11-09 19:49:36
SpringBoot如何集成PageHelper分页功能
2022-10-22 03:18:34
JavaWeb工程中集成YMP框架快速上手
2023-11-24 12:15:12
![](https://img.aspxhome.com/file/2023/9/58709_0s.png)
Java内存模型JMM与volatile
2022-03-25 09:33:50
![](https://img.aspxhome.com/file/2023/4/62204_0s.png)
Java 数据结构与算法系列精讲之排序算法
2023-11-01 13:25:40
![](https://img.aspxhome.com/file/2023/4/65304_0s.jpg)
java控制台输出图书馆管理系统
2022-06-13 01:29:29
![](https://img.aspxhome.com/file/2023/4/61284_0s.jpg)
通过源码角度看看AccessibilityService
2023-07-25 09:31:43
![](https://img.aspxhome.com/file/2023/2/84752_0s.jpg)
基于jQuery获取table数据发送到后端
2023-07-22 22:07:43
springboot集成swagger3与knife4j的详细代码
2023-11-27 18:22:58
![](https://img.aspxhome.com/file/2023/1/60471_0s.png)
详解Spring Boot Profiles 配置和使用
2021-10-05 22:54:57
2020JDK1.8安装教程详解(一次就可安装成功)
2023-11-28 04:08:58
![](https://img.aspxhome.com/file/2023/3/60253_0s.png)
SpringBoot瘦身打包部署的实现
2021-09-09 16:54:21
![](https://img.aspxhome.com/file/2023/3/66673_0s.png)