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,不仅可以对文件进行压缩,还 ...
随机推荐
- Spring Data Redis Stream的使用
一.背景 Stream类型是 redis5之后新增的类型,在这篇文章中,我们实现使用Spring boot data redis来消费Redis Stream中的数据.实现独立消费和消费组消费. 二. ...
- @RestController注解的作用
原文出自"https://www.cnblogs.com/yaqee/p/11256047.html" 一.在Spring中@RestController的作用等同于@Contro ...
- .net工程师学习vue的心路历程(三)
vue cli3没记错的话是在2019年8月份yyx个人正式声明发布. 接下来就开始我们的vue cli3的方式创建vue项目.明白一点,vue cli3遵循的一个原则就是 "0配置&quo ...
- [luogu5162]WD与积木
设$g_{n}$表示$n$个积木放的方案数,枚举最后一层所放的积木,则有$g_{n}=\sum_{i=1}^{n}c(n,i)g_{n-i}$(因为积木有编号的所以要选出$i$个) 将组合数展开并化简 ...
- spring security 认证源码跟踪
spring security 认证源码跟踪 在跟踪认证源码之前,我们先根据官网说明一下security的内部原理,主要是依据一系列的filter来实现,大家可以根据https://docs.sp ...
- html中引入外部js文件,使用外部js文件里的方法
外部js文件1: /** * 加了window.onload 后,直接引入js文件即可 * 页面资源全部加载完毕后会自动调用window.onload里的回调函数 */ window.addEvent ...
- CF1592F2 Alice and Recoloring 2
目前在看贪心/构造/DP 杂题选做,发现一道非常不错的结论题,具有启发意义. 先说明如下结论 结论一:如何怎么样都不会使用二和三操作 证明: 二三操作显然可以通过两次一操作达到,而其操作费用大于两次一 ...
- spring通过注解注册bean的方式+spring生命周期
spring容器通过注解注册bean的方式 @ComponentScan + 组件标注注解 (@Component/@Service...) @ComponentScan(value = " ...
- Boussinesq 近似及静压假定,内外模分离方法(附录A)
0.Formulation of the RANS equations [1] 不可压缩流体控制方程 \[\begin{array}{l l} \frac{\partial u}{\partial x ...
- 充分利用nginx的reload功能平滑的上架和更新业务
以前更新我们都要停服务更新,不管什么时候更新,都可能有客户在访问,体验不好,二是如果有数据传输,可能会造成数据丢失. nginx reload可以不间断更新配置文件,原理就是当我们修改配置文件发起re ...