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. Python基础(返回函数)

    #我们在函数lazy_sum中又定义了函数f1,并且,内部函数f1可以引用外部函数lazy_sum的参数和局部变量,当lazy_sum返回函数f1时,相关参数和变量都保存在返回的函数中,这种称为&qu ...

  2. Excel - java

    package com.e6soft.project.ExcelUtil; import java.io.BufferedInputStream; import java.io.File; impor ...

  3. 菜鸡的Java笔记 日期操作类

    日期操作类        Date 类与 long 数据类型的转换        SimpleDateFormat 类的使用        Calendar 类的使用                如 ...

  4. 利用Fastjson注入Spring内存马

    此篇文章在于记录自己对spring内存马的实验研究 一.环境搭建 搭建漏洞环境,利用fastjson反序列化,通过JNDI下载恶意的class文件,触发恶意类的构造函数中代码,注入controller ...

  5. 【Python】300行代码搞定HTML模板渲染

    一.前言 模板语言由HTML代码和逻辑控制代码组成,此处@PHP.通过模板语言可以快速的生成预想的HTML页面.应该算是后端渲染不可缺少的组成部分. 二.功能介绍 通过使用学习tornado.bott ...

  6. Java安全之Axis漏洞分析

    Java安全之Axis漏洞分析 0x00 前言 看到个别代码常出现里面有一些Axis组件,没去仔细研究过该漏洞.研究记录一下. 0x01 漏洞复现 漏洞版本:axis=<1.4 Axis1.4 ...

  7. Python实战:截图识别文字,过万使用量版本!(附源码!!)

    前人栽树后人乘凉,以不造轮子为由 使用百度的图片识字功能,实现了一个上万次使用量的脚本. 系统:win10 Python版本:python3.8.6 pycharm版本:pycharm 2021.1. ...

  8. SSM(Spring-MyBatis-SpringMVC)框架整合【完整版】

    整合SSM 01 基本配置文件的关系 web.xml配置DispatcherServlet 02 需要的maven依赖 <!--依赖 1.junit 2.数据库连接池 3.servlet 4.j ...

  9. 8.5 Ingress实现基于域名的多虚拟主机、URL转发、及多域名https实现等案例

    1.什么是Ingress Ingress 公开了从k8s集群外部到集群内服务的 HTTP 和 HTTPS 路由. 流量路由由 Ingress 资源上定义的规则控制. 可以将 Ingress 配置为服务 ...

  10. .NET E F(Entity Framework)框架 DataBase First 和 Code First 简单用法。

    EF是微软.NET平台官方的ORM(objet-relation mapping),就是一种对象-关系 映射,是将关系数据库种的业务数据用对象的形式表现出来,并通过面向对象的方式讲这些对象组织起来,实 ...