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 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 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 文件压缩_java实现文件压缩相关推荐

  1. java gzip压缩_Java GZIP示例–压缩和解压缩文件

    java gzip压缩 Welcome to Java GZIP example. GZIP is one of the favorite tool to compress file in Unix ...

  2. java文本压缩算法_java 什么算法压缩文件最小

    展开全部 有三种方式实现java压缩: 1.jdk自带的包java.util.zip.ZipOutputStream,不足之处,文件(夹)名称32313133353236313431303231363 ...

  3. java zip 创建目录_Java实现Zip压缩目录中的所有文件

    java中将一个文件夹下所有的文件压缩成一个文件,然import java.io.*; import java.util.zip.*; public class CompressD { // 缓冲 s ...

  4. java mp3文件压缩_java实现文件压缩

    java实现文件压缩:主要是流与流之间的传递 代码如下: package com.cst.klocwork.service.zip; import java.io.File; import java. ...

  5. java 多种类型文件复制_java多种文件复制方式以及效率比较

    1.背景 java复制文件的方式其实有很多种,可以分为 传统的字节流读写复制FileInputStream,FileOutputStream,BufferedInputStream,BufferedO ...

  6. java io文件操作_java IO 文件操作方法总结

    java IO 文件操作方法总结 对于输入输出的理解: 输入输出,以程序为参考点,外部数据进入程序,通过输入流完成.程序将数据给外部设备,通过输出流完成. 文件Io的操作 //获取文件 File fi ...

  7. java class 结构_Java class文件的结构

    Java class文件的结构 class文件是Java源代码编译之后产生的二进制文件,代码中的各个项目严格按照Java的规范组织. class文件以一张表的形式组织代码中的各个部分: 名称 释义 大 ...

  8. java底层 文件操作_JAVA的文件操作【转】

    11.3 I/O类使用 由于在IO操作中,需要使用的数据源有很多,作为一个IO技术的初学者,从读写文件开始学习IO技术是一个比较好的选择.因为文件是一种常见的数据源,而且读写文件也是程序员进行IO编程 ...

  9. java读取空格_java 读取文件路径空格和中文的处理

    应用部署时,发生文件读取错误,发现是部署路径中含有空格的文件夹名,然后把应用服务器位置迁移了. 从网上找到如下方案: 1, TestURL().class.getResource("&quo ...

最新文章

  1. 【收藏】Java多线程/并发编程大合集
  2. 女生学软件测试有哪些优势
  3. 自动化测试的优势和局限性有哪些
  4. 最火移动端跨平台方案盘点:React Native、weex、Flutter
  5. jms mdb_MDB!= JMS,反之亦然
  6. HDFS机架感知概念及配置实现
  7. HUB,交换机,路由器,MODEM都有什么区别???
  8. php日志缓存,php – Symfony和Docker – 缓存和日志目录权...
  9. 平板电脑有哪些品牌_平板电脑充电柜使用要注意哪些?安和力
  10. 在 Linux 上监控 CPU 和 GPU 温度
  11. jQuery 源码系列(二)init 介绍
  12. 实用机器人设计(一)-机器人技术基础
  13. 小学生python编程教程-python 小学生教程|怎么让一个小学生学会Python?
  14. ROS创建工作空间和source的解释
  15. SAP PS 第15节 预算管理
  16. 微信小程序不能使用本地图片当背景图片的解决方法
  17. 云原生一站式DevOps平台----云效
  18. 卡券、直充订单列表(post 表单提交)接口
  19. 人员定位系统如何构建企业安全防护体系?
  20. Windows开启IIS服务器,并发布网站

热门文章

  1. Jenkins 流水线 获取git 分支列表_某小型公司持续集成工具 jenkins 实践
  2. MATLAB学习笔记(七)
  3. java 多个数字_java 输入多个数字
  4. angular 字符串转换成数字_Python成为专业人士笔记–String字符串方法
  5. 【系统架构设计师】软考高级职称,一次通过,2017年下半年系统架构设计师考试论文真题(论软件架构风格)
  6. 变分法和变分贝叶斯推断
  7. Python模板设置
  8. Python机器学习:PCA与梯度上升:06scikit中的PCA
  9. Java如何隐藏控制按键动画_Java动画短片当不移动鼠标光标时
  10. python中如何统计元组中元素的个数_Python:count直到列表中的元素是一个元组