今天通过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压缩文件和解压缩的更多相关文章

  1. Java学习笔记之I/O流(读取压缩文件以及压缩文件)

    1.读取压缩文件:ZipInputStream 借助ZipFile类的getInputStream方法得到压缩文件的指定项的内容,然后传递给InputStreamReader类的构造方法,返回给Buf ...

  2. C#压缩文件,C#压缩文件夹,C#获取文件

    using System; using System.Data; using System.Configuration; using System.Collections.Generic; using ...

  3. cocos2d-x教程3:用php或DOS批处理命令来转换文件和解压缩zip

    在cocos2d-x使用中,须要不停的转换文件和压缩或解压文件.假设全人工来做,太麻烦了,且easy出错. 我如今把一些用的到批处理贴出来,供大家使用 自己主动把dat文件按数字排序重命名gz.DOS ...

  4. linux 压缩文件 及压缩选项详解

    本文介绍linux下的压缩程序tar.gzip.gunzip.bzip2.bunzip2.compress.uncompress. zip. unzip.rar.unrar等程式,以及如何使用它们对. ...

  5. linux下tar gz bz2 tgz z等众多压缩文件的压缩与解压方法

    Linux下最常用的打包程序就是tar了,使用tar程序打出来的包我们常称为tar包,tar包文件的命令通常都是以.tar结尾的.生成tar包后,就可以用其它的程序来进 行压缩了,所以首先就来讲讲ta ...

  6. C#压缩文件 不压缩路径

    我想把 E:\\AA\BB\11.txt 压缩后存入 E:\\AA1\BB1\11.rar 但是当我解压( E:\\AA1\BB1\11.rar)的时候,发现:11.txt 不是在 E:\\AA1\B ...

  7. python 压缩文件(解决压缩路径问题)

    #压缩文件 def Zip_files(): datapath = filepath # 证据路径 file_newname = datapath + '.zip' # 压缩文件的名字 log.deb ...

  8. 使用zip.js压缩文件和解压文件

    zip.js官方网站为:https://stuk.github.io/jszip/ 在此说明,下面的例子基本上来自官方示例,大家可以做参考,官方示例地址为:https://stuk.github.io ...

  9. Linux 压缩文件 和解压文件

    .zip 解压:unzip FileName.zip 压缩:zip FileName.zip DirName .rar 解压:rar -x FileName.zip 压缩:rar -a FileNam ...

随机推荐

  1. C++控制台闪回;编译器警告C4305,C4244

    这是我以前解决问题时,收集在印象笔记里的内容,为了以后整理方便,把它转移至这里.以下内容,均来自微软官方网站相关.     问题:C++控制台闪回     解决办法: 1,在程序结尾添加system( ...

  2. python基础-面向对象编程之封装、访问限制机制和property

    面向对象编程之封装 封装 定义:将属性和方法一股脑的封装到对象中,使对象可通过"对象."的方式获取或存储数据. 作用:让对象有了"."的机制,存取数据更加方便 ...

  3. MySQL数据每日备份

    1.window下通过命令方式 @echo offset "Ymd=%date:~,4%-%date:~5,2%-%date:~8,2%%time:~0,2%%time:~3,2%" ...

  4. MySQL8.0 新特性 Hash Join

    概述&背景 MySQL一直被人诟病没有实现HashJoin,最新发布的8.0.18已经带上了这个功能,令人欣喜.有时候在想,MySQL为什么一直不支持HashJoin呢?我想可能是因为MySQ ...

  5. SpringAOP之使用切入点创建通知

    之前已经说过了SpringAOP中的几种通知类型以及如何创建简单的通知见地址 一.什么是切入点 通过之前的例子中,我们可以创建ProxyFactory的方式来创建通知,然后获取目标类中的方法.通过不同 ...

  6. Python使用百度地图API根据地名获取相应经纬度

    今天有个需求,要根据地名获取经纬度坐标值. 于是我第一想法:打开百度地图,手动输入地名,获取.显然当地名较少时,可实施.然而,当地名较多时,此方法显然工作量很大. 于是,第二想法:代码获取,请求百度地 ...

  7. mysql 基础知识整理

    什么是MySQL? MySQL 是一种关系型数据库,在Java企业级开发中非常常用,因为 MySQL 是开源免费的,并且方便扩展.阿里巴巴数据库系统也大量用到了 MySQL,因此它的稳定性是有保障的. ...

  8. 原生js删除增加修改class属性

    其实html5已经扩展了class操作的相关API,其中classList属性就以及实现了class的增删和判断. HTML DOM classList 属性 classList属性的方法有: add ...

  9. linux任务计划cron、chkconfig工具、systemd管理服务、unit和target介绍

    第8周第1次课(5月14日) 课程内容: 10.23 linux任务计划cron10.24 chkconfig工具10.25 systemd管理服务10.26 unit介绍10.27 target介绍 ...

  10. cmd for install pygame in python 3.7

    Higher version Python better and convinient to use! Down load pygame whl file: C:\Work\software>p ...