java实现文件压缩:主要是流与流之间的传递

代码如下:

package com.cst.klocwork.service.zip;

import java.io.File;

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream; import org.apache.logging.log4j.util.Strings; /**
* ZipUtils
* @author ZENG.XIAO.YAN
* @date 2017年11月19日 下午7:16:08
* @version v1.0
*/
public class ZipUtils { private static final int BUFFER_SIZE = 2 * 1024;
//1.只传一个压缩文件的()
public static void toZip(String sourceDir) {
toZip(sourceDir,null,true);
}
//2.目标文件 + 压缩文件的位置 (名字用默认)
public static void toZip(String sourceDir,String target) {
String fileName = new File(sourceDir).getName();
target = target+"/"+fileName.substring(0, fileName.lastIndexOf('.'))+".zip";
toZip(sourceDir,target,true);
}
//3.目标文件 + 压缩文件的位置 + 目标文件命名 + 文件夹中的文件是否在源目录
/**
* 压缩成ZIP 方法1
* @param sourceDir 压缩文件夹路径
* @param targetDir 压缩后文件的路径名称
* @param KeepDirStructure 是否保留原来的目录结构,true:保留目录结构;
* false:所有文件跑到压缩包根目录下(注意:不保留目录结构可能会出现同名文件,会压缩失败)
* @throws RuntimeException 压缩失败会抛出运行时异常
*/
public static void toZip(String sourceDir, String targetDir, boolean KeepDirStructure)
throws RuntimeException{
//Files.getDir(CstDir.config) File sourceFile = new File(sourceDir);
String sourcePath = sourceFile.getParentFile().toString();
String fileName = sourceFile.getName(); long start = System.currentTimeMillis();
ZipOutputStream zos = null ;
try {
FileOutputStream out = null;
if(Strings.isEmpty(targetDir)) {
if(sourceFile.isDirectory()) {
out = new FileOutputStream(new File(sourcePath+"/"+fileName+".zip"));
}else {
out = new FileOutputStream(new File(sourcePath+"/"+fileName.substring(0, fileName.lastIndexOf('.'))+".zip"));
}
}else {
out = new FileOutputStream(new File(targetDir)); } zos = new ZipOutputStream(out);
compress(sourceFile,zos,sourceFile.getName(),KeepDirStructure);
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();
}
}
} } /**
* 压缩成ZIP 方法2
* @param srcFiles 需要压缩的文件列表
* @param out 压缩文件输出流
* @throws RuntimeException 压缩失败会抛出运行时异常
*/
//多个文件一起压缩,若上级目录为根节点,则压缩后的名字与最后一个文件的命名相同
//若上级目录不空,则压缩后的名字为上级目录的名字
public static void toZips(List<File> srcFiles , String targetDir)throws RuntimeException {
long start = System.currentTimeMillis(); FileOutputStream out = null;
String targetName = "";
String sourcePath = srcFiles.get(0).getParent(); ZipOutputStream zos = null ;
try {
if(Strings.isEmpty(targetDir)) {
if(srcFiles.size()>0 && srcFiles!=null) {
targetName = srcFiles.get(srcFiles.size()-1).getName();//获得最后一个文件的名字
targetName = targetName.substring(0, targetName.lastIndexOf('.'));
}
out = new FileOutputStream(new File(sourcePath+"/"+targetName+".zip")); }else {
out = new FileOutputStream(new File(targetDir));
}
zos = new ZipOutputStream(out);
for (File srcFile : srcFiles) {
compress(srcFile,zos,srcFile.getName(),true);
}
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();
}
}
}
} /**
* 递归压缩方法
* @param sourceFile 源文件
* @param zos zip输出流
* @param name 压缩后的名称
* @param KeepDirStructure 是否保留原来的目录结构,true:保留目录结构;
* false:所有文件跑到压缩包根目录下(注意:不保留目录结构可能会出现同名文件,会压缩失败)
* @throws Exception
*/
private static void compress(File sourceFile, ZipOutputStream zos, String name,
boolean KeepDirStructure) throws Exception{
byte[] buf = new byte[BUFFER_SIZE];
if(sourceFile.isFile()){
// 向zip输出流中添加一个zip实体,构造器中name为zip实体的文件的名字
zos.putNextEntry(new ZipEntry(name));
// copy文件到zip输出流中
int len;
FileInputStream in = new FileInputStream(sourceFile);
while ((len = in.read(buf)) != -1){
zos.write(buf, 0, len);
}
// Complete the entry
zos.closeEntry();
in.close();
} else {
File[] listFiles = sourceFile.listFiles();
if(listFiles == null || listFiles.length == 0){
// 需要保留原来的文件结构时,需要对空文件夹进行处理
if(KeepDirStructure){
// 空文件夹的处理
zos.putNextEntry(new ZipEntry(name + "/"));
// 没有文件,不需要文件的copy
zos.closeEntry();
} }else {
for (File file : listFiles) {
// 判断是否需要保留原来的文件结构
if (KeepDirStructure) {
// 注意:file.getName()前面需要带上父文件夹的名字加一斜杠,
// 不然最后压缩包中就不能保留原来的文件结构,即:所有文件都跑到压缩包根目录下了
compress(file, zos, name + "/" + file.getName(),KeepDirStructure);
} else {
compress(file, zos, file.getName(),KeepDirStructure);
}
}
}
}
} public static void main(String[] args) throws Exception { /** 测试压缩方法1 */
FileOutputStream fos1 = new FileOutputStream(new File("D:/test.zip"));
ZipUtils.toZip("D:/test/交接", null,true); /** 测试压缩方法2 */
List<File> fileList = new ArrayList<>();
fileList.add(new File("D:\\test\\交接")); fileList.add(new File("D:\\test\\day哈哈12.txt"));
// FileOutputStream fos2 = new FileOutputStream(new File("c:/mytest02.zip"));
ZipUtils.toZips(fileList,"D:\\test1111.zip");
}
}

  

java实现文件压缩的更多相关文章

  1. Java实现文件压缩与解压

    Java实现ZIP的解压与压缩功能基本都是使用了Java的多肽和递归技术,可以对单个文件和任意级联文件夹进行压缩和解压,对于一些初学者来说是个很不错的实例.(转载自http://www.puiedu. ...

  2. Java实现文件压缩与解压[zip格式,gzip格式]

    Java实现ZIP的解压与压缩功能基本都是使用了Java的多肽和递归技术,可以对单个文件和任意级联文件夹进行压缩和解压,对于一些初学者来说是个很不错的实例. zip扮演着归档和压缩两个角色:gzip并 ...

  3. java中 文件压缩处理

    public static void main(String[] args) throws IOException { File file=new File("./mhxx_configs. ...

  4. Java 多文件压缩成一个文件工具类

    简单修改来自博客园勇闯天涯zfc的博客 一.内容 ①使用 Java 将多个文件打包压缩成一个压缩文件: ②主要使用 java.io 下的类 二.源代码:ZIPUtil .java import jav ...

  5. Java—将文件压缩为zip文件

    import java.io.BufferedInputStream; import java.io.BufferedOutputStream; import java.io.File; import ...

  6. Java 批量文件压缩导出,并下载到本地

    主要用的是org.apache.tools.zip.ZipOutputStream  这个zip流,这里以Execl为例子. 思路首先把zip流写入到http响应输出流中,再把excel的流写入zip ...

  7. java代理使用 apache ant实现文件压缩/解压缩

    [背景] 近日在研究web邮件下载功能,下载的邮件能够导入foxmail邮件client.可是批量下载邮件还需将邮件打成一个压缩包. 从网上搜索通过java实现文件压缩.解压缩有非常多现成的样例. [ ...

  8. 文件压缩跟解压(本地&Linux服务器)

    远程解压需要的jar包: <dependency> <groupId>commons-net</groupId> <artifactId>commons ...

  9. java 文件压缩和解压(ZipInputStream, ZipOutputStream)

    最近在看java se 的IO 部分 , 看到 java 的文件的压缩和解压比较有意思,主要用到了两个IO流-ZipInputStream, ZipOutputStream,不仅可以对文件进行压缩,还 ...

随机推荐

  1. 常用的package.json以及React相关

    常用的package.json以及React相关 前言 package.json 的简单介绍 简单版的 package.json 必备属性(name & version) name 字段 ve ...

  2. ABAP——系统状态&用户状态修改、查询

    前言:在ABAP开发中有时候会涉及到状态的变更,比如销售订单的系统状态变更未审批->已审批.设备的在运->报废等,在这里就需要用到标准函数I_CHANGE_STATUS.STATUS_CH ...

  3. 9组-Ahlpa-6/3

    一.基本情况 队名:不行就摆了吧 组长博客:https://www.cnblogs.com/Microsoft-hc/p/15546622.html 小组人数: 8 二.冲刺概况汇报 卢浩玮 过去两天 ...

  4. Django 小实例S1 简易学生选课管理系统 11 学生课程业务实现

    Django 小实例S1 简易学生选课管理系统 第11节--学生课程业务实现 点击查看教程总目录 作者自我介绍:b站小UP主,时常直播编程+红警三,python1对1辅导老师. 课程模块中,学生需要拥 ...

  5. Swift-技巧(五)设置圆角的代码

    摘要 实现控件圆角的代码时,会不假思索的写 cornerRadius 和 masksToBounds,因为搜索得到的设置圆角的代码就是这样.今天突发奇想,为什么要写 masksToBounds? 打个 ...

  6. [loj2339]通道

    类似于[loj2553] 对第一棵树边分治,对第二棵树建立虚树,并根据直径合并的性质来处理第三棵树(另外在第三棵树中计算距离需要使用dfs序+ST表做到$o(1)$优化) 总复杂度为$o(n\log^ ...

  7. 【JavaSE】JDK配置

    Java开发环境配置 2020-09-10  08:32:20  by冲冲 1. Windows7安装JDK 1.1 下载JDK ① 下载地址:http://www.oracle.com/techne ...

  8. 最难忘的一次bug:谢谢实习时候爱学习的自己

    前言 时间的车轮一直向前不停,试图在时光洪流中碾碎一些久远的记忆.虽然记忆中的人离我越来越远,但是故事却越来越深刻. 当在博客园看到这次的正文题目是"最难忘的bug",脑海里瞬间浮 ...

  9. BehaviorTree.CPP行为树BT的介绍(一)

    节点类型 ControlNode是可以具有1到N个子节点的节点.一旦接收到tick,tick可以传播到一个或多个子节点. DecoratorNodes与ControlNode相似,但只能有一个子节点. ...

  10. 题解 P5320 - [BJOI2019]勘破神机(推式子+第一类斯特林数)

    洛谷题面传送门 神仙题(为什么就没能自己想出来呢/zk/zk) 这是我 AC 的第 \(2\times 10^3\) 道题哦 首先考虑 \(m=2\) 的情况,我们首先可以想到一个非常 trivial ...