《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 ...
随机推荐
- python进程池与线程池
为什么会进行池化? 一切都是为了效率,每次开启进程都会分配一个属于这个进程独立的内存空间,开启进程过多会占用大量内存,系统调度也会很慢,我们不能无限的开启进程. 进程池原来大概如下图 假设有100个任 ...
- 记一次LDAP主从同步配置
LDAP主从同步 OpenLDAP在2.3版本之前的同步复制带有一系列缺点如只支持一主多从模式等,在此缺点就不多说,下文着重介绍一下OpenLDAP V2.4以后的同步负复制功能 同步功能 2.4版最 ...
- python3 之 字符串编码小结(Unicode、utf-8、gbk、gb2312等)
python3 解释器默认编码为Unicode,由str类型进行表示.二进制数据使用byte类型表示. 字符串通过编码转换成字节串,字节码通过解码成为字符串. encode:str-->byte ...
- The absolute uri: [http://java.sun.com/jsp/jstl/core] cannot be resolved in either web.xml or the jar files deployed with this application] with root cause异常处理及解释
1.问题描述: 在web的jsp文件中想用jstl这个标准库,在运行的时候很自然的引用jar包如下: <dependency> <groupId>javax.servlet.j ...
- 堆的python实现及其应用
堆的概念 优先队列(priority queue)是一种特殊的队列,取出元素的顺序是按照元素的优先权(关键字)大小,而不是进入队列的顺序,堆就是一种优先队列的实现.堆一般是由数组实现的,逻辑上堆可以被 ...
- windows下PyCharm安装及使用 【转自 https://blog.csdn.net/yctjin/article/details/70307933?locationNum=11&fps=1】
一.首先安装pycharm,可以参考这篇文章:http://www.jianshu.com/p/042324342bf4 搭建环境 1.win10_X64,其他Win版本也可以.2.PyCharm版本 ...
- MySQL的存储(一、连接数据库)
准备工作: 确保安装MySql 安装PyMySQL库 连接数据库: 这里首先尝试连接下数据库,假设当前MySQL运行在本地,用户名为root,密码为123456,运行端口为3306. 通过PyMySQ ...
- 5G,仅仅是更快的网速吗?
前不久参加了华为的Dev Summit 2020开发者大会,听到了关于5G的一些分享,刚好最近对5G有一些自己的思考,在此分享给大家. 什么是5G 在这里我不想列举各种晦涩难懂的术语,简单说来,5G就 ...
- php mysql_connect 在同一host下多数据库mysql_select_db()的bug .
操作方法 创建两个数据库test1 test2 同一个host下面 分别在两个数据库中创建表 -- ---------------------------- -- Table structure fo ...
- php上传下载文件
之前做一个上传下载的项目,发现网上的和自己需求不是很一样,翻阅了下书籍和整理了下网上的一些代码.做了一个上传下载的demo,上传通过php本身的uploadfile函数,并返回以时间戳命名的文件名后, ...