《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 ...
随机推荐
- ubuntu 16.04源码编译OpenCV教程 | compile opencv on ubuntu 16.04
本文首发于个人博客https://kezunlin.me/post/15f5c3e8/,欢迎阅读! compile opencv on ubuntu 16.04 Series Part 1: comp ...
- C# - VS2019 WinFrm应用程序开发报表 - ReportViewer控件初涉
前言 简单报表我们可以通过label.textBox和PrintDialog来实现,但是一般在实际生产过程中,用户的报表需求一般都是比较复杂的. 本篇主要记录对于传统中国式复杂报表的处理方法和解决思路 ...
- Java数组使用以及foreach循环
Java数组使用以及foreach循环 二话不说,先甩一个简单的程序: final int NUM= 10; int[] arrays = new int[NUM]; System.out.print ...
- 《手把手教你》系列练习篇之2-python+ selenium自动化测试(详细教程)
1. 简介 今天我们还是继续练习练习基本功,各位小伙伴要耐住住性子,要耐得住寂寞啊,不要急躁,后面你会感谢你在前边的不断练习的.到后面也是检验你前边的学习成果的一次很好实践. 本文介绍如何通过link ...
- Python3学习-基础
1.直接运行.py文件 在Windows上是不行的,但是在Mac和Linux上是可以的,方法是在.py文件的第一行加上一个特殊的注释: #!/usr/bin/env python3 print('he ...
- 基于 HTML5 + WebGL 的太阳系 3D 展示系统
前言 近年来随着引力波的发现.黑洞照片的拍摄.火星上存在水的证据发现等科学上的突破,以及文学影视作品中诸如<三体>.<流浪地球>.<星际穿越>等的传播普及,宇宙空间 ...
- 记一次MySQL数据库导入错误
昨天在转数据的时候,控制台报出了下面这个warning: Warning: Data truncated for column '控制距离' at row 1 字面上意思应该是:控制距离这一字段在第一 ...
- Chapter 03—Getting Started with graphs
例01:一个简单的例子 一. 图形参数 1. 符号和线条 例02: plot(dose,drugA,type="b",lty=3,lwd=3,pch=1 ...
- AI:为你写诗,为你做不可能的事
最近,一档全程高能的神仙节目,高调地杀入了我们的视野: 没错,就是撒贝宁主持,董卿.康辉等央视名嘴作为评审嘉宾,同时集齐央视"三大名嘴"同台的央视<主持人大赛>,这够不 ...
- shell 脚本运行 hive sql
#!/b START=$(date +%s); datebegin=`date -d "$1" "+%Y%m%d"` dateend=`date -d &quo ...