java实现文件压缩
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实现文件压缩的更多相关文章
- Java实现文件压缩与解压
Java实现ZIP的解压与压缩功能基本都是使用了Java的多肽和递归技术,可以对单个文件和任意级联文件夹进行压缩和解压,对于一些初学者来说是个很不错的实例.(转载自http://www.puiedu. ...
- Java实现文件压缩与解压[zip格式,gzip格式]
Java实现ZIP的解压与压缩功能基本都是使用了Java的多肽和递归技术,可以对单个文件和任意级联文件夹进行压缩和解压,对于一些初学者来说是个很不错的实例. zip扮演着归档和压缩两个角色:gzip并 ...
- java中 文件压缩处理
public static void main(String[] args) throws IOException { File file=new File("./mhxx_configs. ...
- Java 多文件压缩成一个文件工具类
简单修改来自博客园勇闯天涯zfc的博客 一.内容 ①使用 Java 将多个文件打包压缩成一个压缩文件: ②主要使用 java.io 下的类 二.源代码:ZIPUtil .java import jav ...
- Java—将文件压缩为zip文件
import java.io.BufferedInputStream; import java.io.BufferedOutputStream; import java.io.File; import ...
- Java 批量文件压缩导出,并下载到本地
主要用的是org.apache.tools.zip.ZipOutputStream 这个zip流,这里以Execl为例子. 思路首先把zip流写入到http响应输出流中,再把excel的流写入zip ...
- java代理使用 apache ant实现文件压缩/解压缩
[背景] 近日在研究web邮件下载功能,下载的邮件能够导入foxmail邮件client.可是批量下载邮件还需将邮件打成一个压缩包. 从网上搜索通过java实现文件压缩.解压缩有非常多现成的样例. [ ...
- 文件压缩跟解压(本地&Linux服务器)
远程解压需要的jar包: <dependency> <groupId>commons-net</groupId> <artifactId>commons ...
- java 文件压缩和解压(ZipInputStream, ZipOutputStream)
最近在看java se 的IO 部分 , 看到 java 的文件的压缩和解压比较有意思,主要用到了两个IO流-ZipInputStream, ZipOutputStream,不仅可以对文件进行压缩,还 ...
随机推荐
- Vue.js教程 1.前端框架学习介绍
Vue.js教程 1.前端框架学习介绍 什么是Vue.js 为什么要学习流行框架 什么是Vue.js Vue.js 是目前最火的一个前端框架,React是最流行的一个前端框架(React除了开发网站, ...
- redis数据存储的细节
redis是一个K-V NoSql非关系型数据库,redis有物种数据类型,分别是String,Hash,list,set,zset:这五种类型都是针对K-V中的V设计的. 1.总体介绍:关于redi ...
- SpringCloud升级之路2020.0.x版-34.验证重试配置正确性(1)
本系列代码地址:https://github.com/JoJoTec/spring-cloud-parent 在前面一节,我们利用 resilience4j 粘合了 OpenFeign 实现了断路器. ...
- 带allow-create的el-select限制长度
需求:给el-select添加新增字段长度限制且新增内容不能为空 1.首先给el-select绑定一个id(例如:selectSku),这个id会传到组件里面,绑定在那个input上面, <el ...
- [loj3528]位移寄存器
当$s=0$时(求最小值): 若$x_{0},x_{1},...,x_{n-1}$和$y_{0},y_{1},...,y_{n-1}$像题中所给的方式存储在$r[0][0..nk-1]$和$r[1][ ...
- [bzoj2668]交换棋子
基本思路是,要让所有黑点都相对应(所以首先判断黑点的个数).如果没有交换限制,可以按以下方法建图:源点向所有初始黑点连(1,0)的边,最终黑点向汇点连(1,0)的边,相邻的两点连边(inf,1),最小 ...
- [bzoj3304]带限制的最长公共子序列
用f[i][j][k]表示s1前i个字符.s2前j个字符的LCS且包括s3前k个字符的最长前缀,然后对其某一维滚动,实现时细节比较多 1 #include<bits/stdc++.h> 2 ...
- springboot和mybatis集成
springboot和mybatis集成 pom <?xml version="1.0" encoding="UTF-8"?> <proje ...
- ant命令
ant -help 帮助(ant -h) ant -projecthelp 列举xml中重要的部分 (ant -p) ant -version 查看版本 ant -diagnostics 打印所有环境 ...
- 联盛德 HLK-W806 (三): 免按键自动下载和复位
目录 联盛德 HLK-W806 (一): Ubuntu20.04下的开发环境配置, 编译和烧录说明 联盛德 HLK-W806 (二): Win10下的开发环境配置, 编译和烧录说明 联盛德 HLK-W ...