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
0
投稿
猜你喜欢
- Java7引入了Fork Join的概念,来更好的支持并行运算。顾名思义,Fork Join类似与流程语言的分支,合并的概念。也就是说Jav
- Java 8支持动态语言,看到了很酷的Lambda表达式,对一直以静态类型语言自居的Java,让人看到了Java虚拟机可以支持动态语言的目标
- Reflections通过扫描classpath,索引元数据,并且允许在运行时查询这些元数据。使用Reflections可以很轻松的获取以下
- 什么是NIO?线程在处理数据时,如果线程还处于将数据从channel读到buffer的这段时间内,线程可以去做别的事情,等数据都读到buff
- 在SpringAMQP的发送方法中,接收消息的类型是Object,也就是说我们可以发送任意对象类型的消息,SpringAMQP会帮我们序列化
- 今天被数据大神说了,对接第三方接口返回的json字段我想用驼峰形式,他说我这样不专业。所以就改了,认怂。记住以后再次对接rest接口,返回的
- try catch finally组合:检测异常,并传递给catch处理,并在finally中进行资源释放。try catch组合 : 对代
- 本文实例讲述了Android TextView跑马灯效果实现方法。分享给大家供大家参考,具体如下:public class MyTextVi
- Java平台的垃圾收集机制显著提高了开发者的效率,但是一个实现糟糕的垃圾收集器可能过多地消耗应用程序的资源。在Java虚拟机性能优化系列的第
- 前言本文主要给大家介绍了关于Spring4自定义@Value功能的相关内容,使用的Spring版本4.3.10.RELEASE,下面话不多说
- jol(java object layout)需要的依赖<dependency> <
- 有很多同学肯定想学习opencv相关的知识,但是有些情况下每建一次项目都要重新引入下各种文件是不是很苦恼,所以我也面临了这个问题,在网上看到
- 人机猜拳小游戏,只要用到的java面向对象的思维模式。本游戏中有游戏玩家和计算机两个参与者。玩家和计算机都有的属性是姓名和得分。共分为4个类
- Java中可以使用关键字synchronized进行线程同步控制,实现关键资源顺序访问,避免由于多线程并发执行导致的数据不一致性等问题。sy
- 大致分为以下几个方面:一些查询指令整理使用SQL语句进行特殊查询检测表字段是否存在数据库升级数据库表字段赋初始值一、查询指令整理1.链式执行
- Java中有哪些队列ArrayBlockingQueue 使用ReentrantLockLinkedBlockingQueue 使用Reen
- 0.前言HashMap简述:HashMap 基于哈希表的 Map 接口实现,是以 key-value 存储形式存在,即主要用来存放键值对。H
- 项目中用到用户定义运算公式进行就算的需求,这样需要进行字符串四则运算解析,下面提供字符串公式四则运算解析与计算工具类,需要的同学可参考。工具
- 背景为了了解Seata AT模式的原理,我通过源码解读的方式画出了Seata AT模式启动的图示:如果是基于Springboot项目的话,项
- 判断某字符串是否为空,为空的标准是str==null或str.length()==01.下面是StringUtils判断是否为空的示例:St