今天通过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. 执行yaml.load()出现警告信息:YAMLLoadWarning: callingyaml.load() without Loader=..

    执行yaml.load()出现警告信息:YAMLLoadWarning: callingyaml.load() without Loader=... 原因: yaml5.1版本后弃用了yaml.loa ...

  2. 在Spring Security框架下JWT的实现细节原理

    一.回顾JWT的授权及鉴权流程 在笔者的上一篇文章中,已经为大家介绍了JWT以及其结构及使用方法.其授权与鉴权流程浓缩为以下两句话 授权:使用可信用户信息(用户名密码.短信登录)换取带有签名的JWT令 ...

  3. Selenium+Java(三)Selenium元素定位

    前言 使用Selenium做元素定位的时候,需要用到HTML的知识,所以最好是能懂得HTML的基本知识. 一.页面元素的查看(以百度为例) 打开IE浏览器,点击F12进入开发者模式,点击图中红圈圈中的 ...

  4. vue JS实现监听浏览器返回按键事件

    // 这个是监听浏览器回退键的returnButton () { let vm = this; $(document).ready(function () { if (window.history & ...

  5. 使用centos7安装PXE教程

    PXE是一种电脑无盘(即没有硬盘)技术. 预启动执行环境(PXE)指的是那些使得IBM兼容计算机(经常是运行Windows系统)不需要硬盘或是启动软盘就能启动的方法. 通俗点讲就是配置好PXE以后可以 ...

  6. centos7 安装wps

    # cat /etc/redhat-release CentOS Linux release 7.6.1810 (Core) # cat /proc/version Linux version 3.1 ...

  7. PTA 1140 1141 1142 1143

    1140 Look-and-say Sequence 思路:模拟 #include<bits/stdc++.h> using namespace std; typedef long lon ...

  8. 鲲鹏性能优化十板斧(二)——CPU与内存子系统性能调优

    1.1 CPU与内存子系统性能调优简介 调优思路 性能优化的思路如下: l   如果CPU的利用率不高,说明资源没有充分利用,可以通过工具(如strace)查看应用程序阻塞在哪里,一般为磁盘,网络或应 ...

  9. GROUP_CONCAT在组合商品中的使用

    表:combined_product_item -------------------------pid sku quality-------------------------1 sku1 11 s ...

  10. uglify-js 和uglify-es

    uglify-js 它不支持压缩 es6,参考github的issue It seems like uglify-js does not support es6? uglify-js在压缩代码时,遇到 ...