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,不仅可以对文件进行压缩,还 ...
随机推荐
- 了解一下Git的常用语句
简单学习了一下Git,整理了一点常用语句 http连接 git clone https://仓库地址 连接githup cd shop 进入文件夹 git config --global user.n ...
- uni-app nvue页面动态修改导航栏按钮
话不多说上代码 let pages = getCurrentPages() let page = pages[pages.length - 1]; let currentWebview = page. ...
- c++学习笔记1(引用)
引用 格式:类型名&引用名=某变量名: 概念 实例:编写交换整型变量的函数对比 不用引用 实机操作 使用引用 实机操作 实例2:用作函数的返回值 可对函数返回值赋值 常引用 使用格式,在引用前 ...
- Linux——搭建Samba(CIFS)服务器
一.Samba的基本概念 Samba服务:是提供基于Linux和Windows的共享文件服务,服务端和客户端都可以是Linux或Windows操作系统.可以基于特定的用户访问,功能比NFS更强大. S ...
- 搜索系统核心技术概述【1.5w字长文】
前排提示:本文为综述性文章,梳理搜索相关技术,如寻求前沿应用可简读或略过 搜索引擎介绍 搜索引擎(Search Engine),狭义来讲是基于软件技术开发的互联网数据查询系统,用户通过搜索引擎查询所需 ...
- YAPI接口自动鉴权功能部署详解
安装准备 以下操作,默认要求自己部署过yapi,最好是部署过yapi二次开发环境. 无论是选择在线安装或者是本地安装,都需要安装client工具. 1.yapi-cli:npm install yap ...
- [LCT学习时的一些笔记]
会找时间写一篇学习笔记的. \(Access\)的操作是把\(x\)和\(x\)所在原树的顶端点的路径变为一个\(splay\) 对于原树边我们有这样的操作,对每个\(splay\)的顶点维护一个父亲 ...
- THUSC2021 & ISIJ2021 游记
Day -? 4.25 部分摘自日记. 前几天父亲问我 "这个 ISIJ 你要不要报名",我想反正自己 NOIP 和省选那么炸,就当玩玩算了,于是说 "随便吧,那就报呗. ...
- MAC下如何连接安卓(小米)手机进行互传文件?
命令行: brew cask install android-file-transfer AndroidFileTransfer, 在andorid设备和您的mac电脑之间浏览和传输文件: 不论通过什 ...
- RabbitMQ消息中介之Python使用
本文介绍RabbitMQ在python下的基本使用 1. RabbitMQ安装,安装RabbitMQ需要预安装erlang语言,Windows直接下载双击安装即可 RabbitMQ下载地址:http: ...