《Java知识应用》Java压缩文件和解压缩
今天通过Java实现一下:文件的压缩和解压缩。
1. 压缩
准备文件:

准备代码:(压缩)
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.List;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream; public class CompressUtils { public static void main(String[] args) {
//需要压缩的文件路径
List<String> filePathList = new ArrayList<>();
filePathList.add("src\\demo\\knowledgepoints\\compress\\filezip\\1.docx");
filePathList.add("src\\demo\\knowledgepoints\\compress\\filezip\\1.pdf"); //压缩后的文件路径
String zipPath = "src/demo/knowledgepoints/compress/filezip/1.zip";
toZip(filePathList,zipPath);
} /**
* 压缩文件
* @param filePathList
* @param zipPath
* @throws RuntimeException
*/
public static void toZip(List<String> filePathList,String zipPath) throws RuntimeException {
List<File> adjustFiles = new ArrayList<>();
for (String filePath :filePathList){
adjustFiles.add(new File(filePath));
} ByteArrayOutputStream fos2 = new ByteArrayOutputStream();
CompressUtils.toZip(adjustFiles, fos2); BufferedOutputStream output = null;
BufferedInputStream bis = null;
FileOutputStream fos = null;
byte[] fileBytes = fos2.toByteArray();
try {
ByteArrayInputStream byteInputStream = new ByteArrayInputStream(fileBytes); bis = new BufferedInputStream(byteInputStream);
File file = new File(zipPath);
file.createNewFile(); fos = new FileOutputStream(file);
// 实例化OutputString 对象
output = new BufferedOutputStream(fos);
byte[] buffer = new byte[1024];
int length = bis.read(buffer);
while (length != -1) {
output.write(buffer, 0, length);
length = bis.read(buffer);
}
output.flush();
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
if (bis != null) {
bis.close();
}
if (fos != null) {
fos.close();
}
if (output != null) {
output.close();
}
} catch (IOException e0) {
e0.printStackTrace();
}
}
} /**
* 压缩成ZIP
* @param srcFiles 需要压缩的文件列表
* @param out 压缩文件输出流
* @throws RuntimeException 压缩失败会抛出运行时异常
*/
public static void toZip(List<File> srcFiles, OutputStream out) throws RuntimeException {
long start = System.currentTimeMillis();
ZipOutputStream zos = null;
try {
zos = new ZipOutputStream(out);
for (File srcFile : srcFiles) {
byte[] buf = new byte[1024];
zos.putNextEntry(new ZipEntry(srcFile.getName()));
int len;
FileInputStream in = new FileInputStream(srcFile);
while ((len = in.read(buf)) != -1) {
zos.write(buf, 0, len);
}
zos.closeEntry();
in.close();
}
long end = System.currentTimeMillis();
System.out.println("压缩完成,耗时:" + (end - start) + " ms");
} catch (Exception e) {
throw new RuntimeException("zip error from ZipUtils", e);
} finally {
if (zos != null) {
try {
zos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}
运行效果:



1. 解压缩
将刚刚压缩的文件放到新的路径下:

准备代码:(解压缩)
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
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.ZipInputStream; public class CompressUtils { public static void main(String[] args) {
String zipPath = "src\\demo\\knowledgepoints\\compress\\file\\1.zip";
String filePath = "src\\demo\\knowledgepoints\\compress\\file";
zipToFile(zipPath,filePath);
} /**
* zip解压过程
* @param zipPath 压缩文件路径
* @param filePath 解压后文件夹路径
* @throws RuntimeException
*/
public static void zipToFile(String zipPath, String filePath) throws RuntimeException {
long startTime = System.currentTimeMillis(); BufferedInputStream Bin = null; //数据源缓存流
ZipInputStream Zin = null; //数据源
FileOutputStream out = null; //输出流
BufferedOutputStream Bout = null; //输出缓存流
try {
Zin = new ZipInputStream(new FileInputStream(zipPath));//输入源zip路径
Bin = new BufferedInputStream(Zin);
File Fout;
ZipEntry entry;
while ((entry = Zin.getNextEntry()) != null && !entry.isDirectory()) {
Fout = new File(filePath, entry.getName());
if (!Fout.exists()) {
new File(Fout.getParent()).mkdirs();
}
out = new FileOutputStream(Fout);
Bout = new BufferedOutputStream(out);
int bytes;
while ((bytes = Bin.read()) != -1) {
Bout.write(bytes);
}
System.out.println(Fout + "解压成功");
}
long endTime = System.currentTimeMillis();
System.out.println("耗费时间: " + (endTime - startTime) + " ms");
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally {
try {
if (Bin != null) {
Bin.close();
}
if (Zin != null) {
Zin.close();
}
if (Bout != null) {
Bout.close();
}
if (out != null) {
out.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
运行结果:


参考:https://www.cnblogs.com/wangxuemei/p/8360800.html
《Java知识应用》Java压缩文件和解压缩的更多相关文章
- Java学习笔记之I/O流(读取压缩文件以及压缩文件)
1.读取压缩文件:ZipInputStream 借助ZipFile类的getInputStream方法得到压缩文件的指定项的内容,然后传递给InputStreamReader类的构造方法,返回给Buf ...
- C#压缩文件,C#压缩文件夹,C#获取文件
using System; using System.Data; using System.Configuration; using System.Collections.Generic; using ...
- cocos2d-x教程3:用php或DOS批处理命令来转换文件和解压缩zip
在cocos2d-x使用中,须要不停的转换文件和压缩或解压文件.假设全人工来做,太麻烦了,且easy出错. 我如今把一些用的到批处理贴出来,供大家使用 自己主动把dat文件按数字排序重命名gz.DOS ...
- linux 压缩文件 及压缩选项详解
本文介绍linux下的压缩程序tar.gzip.gunzip.bzip2.bunzip2.compress.uncompress. zip. unzip.rar.unrar等程式,以及如何使用它们对. ...
- linux下tar gz bz2 tgz z等众多压缩文件的压缩与解压方法
Linux下最常用的打包程序就是tar了,使用tar程序打出来的包我们常称为tar包,tar包文件的命令通常都是以.tar结尾的.生成tar包后,就可以用其它的程序来进 行压缩了,所以首先就来讲讲ta ...
- C#压缩文件 不压缩路径
我想把 E:\\AA\BB\11.txt 压缩后存入 E:\\AA1\BB1\11.rar 但是当我解压( E:\\AA1\BB1\11.rar)的时候,发现:11.txt 不是在 E:\\AA1\B ...
- python 压缩文件(解决压缩路径问题)
#压缩文件 def Zip_files(): datapath = filepath # 证据路径 file_newname = datapath + '.zip' # 压缩文件的名字 log.deb ...
- 使用zip.js压缩文件和解压文件
zip.js官方网站为:https://stuk.github.io/jszip/ 在此说明,下面的例子基本上来自官方示例,大家可以做参考,官方示例地址为:https://stuk.github.io ...
- Linux 压缩文件 和解压文件
.zip 解压:unzip FileName.zip 压缩:zip FileName.zip DirName .rar 解压:rar -x FileName.zip 压缩:rar -a FileNam ...
随机推荐
- 宋宝华: Linux内核编程广泛使用的前向声明(Forward Declaration)
本文系转载,著作权归作者所有.商业转载请联系作者获得授权,非商业转载请注明出处. 作者:宋宝华 来源: 微信公众号linux阅码场(id: linuxdev) 前向声明 编程定律 先强调一点:在一切可 ...
- 【01】主函数main
java和C#非常相似,它们大部分的语法是一样的,但尽管如此,也有一些地方是不同的. 为了更好地学习java或C#,有必要分清它们两者到底在哪里不同. 首先,我们将探讨主函数main. java的主函 ...
- Java 从入门到进阶之路(九)
之前的文章我们介绍了一下 Java 中的构造方法,接下来我们再来看一下 Java 中的引用型数组类型. 现在我们想定义一个坐标系,然后通过横坐标(row)和纵坐标(col)来确定一个坐标点,代码如下: ...
- node_export 安装
目录 安装部署 环境准备 下载安装 启动测试 安装部署 环境准备 主机名 角色 IP 系统版本 内核版本 es01.k8s.com node01 10.0.20.11 CentOS 7.5 5.1.4 ...
- kubeadm 1.16+ 初始化后 Unable to update cni config: no valid networks found in /etc/cni/net.d
问题描述: 在使用 kubeadm 工具初始化k8s后,并且安装了 flanneld 网络组建后,/var/log/messages 依旧报错, Unable to update cni config ...
- centos7更新php5.4到php5.6/php7
centos7系统yum安装的php版本为5.4. 因业务需求,开发可能需要php5.6环境. 本文应需而生,介绍从php5.4升级到php5.6. 如需更新到php7环境,步骤一样. 如果是线上应用 ...
- 洛谷P2085——最小函数值
题目描述 有n个函数,分别为\(F_1,F_2,...,F_n\).定义\(F_i(x)=A_i*x^2+B_i*x+C_i (x∈N*)\).给定这些\(A_i.B_i和C_i\),请求出所有函数的 ...
- 记录我的 python 学习历程-Day02-while 循环/格式化输出/运算符/编码的初识
一.流程控制之--while 循环 循环就是重复做同一件事,它可以终止当前循环,也可以跳出这一次循环,继续下一次循环. 基本结构(基本循环) while 条件: 循环体 示例 # 这是一个模拟音乐循环 ...
- 批量注释 control+/
批量注释 control+/ You can comment and uncomment lines of code using Ctrl+斜杠.Ctrl+斜杠 comments or uncomme ...
- 1.flask基础
1.flask和django的区别? flask,是一个轻量级的框架,内置了:路由/视图/模板(jinja2)/cookie/session/中间件. 可扩展强,第三方组件非常多,例如:wtforms ...