import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.zip.CRC32;
import java.util.zip.CheckedOutputStream;
import java.util.zip.ZipEntry;
import java.util.zip.ZipInputStream;
import java.util.zip.ZipOutputStream; import com.hyb.constant.Constant; /**
* <p>
* 程序实现了ZIP压缩[compression]
* <p>
* 大致功能包括用了多态,递归等JAVA核心技术,可以对单个文件和任意级联文件夹进行压缩和解压。 需在代码中自定义源输入路径和目标输出路径。
* <p>
* 在本段代码中,实现的是压缩部分
*/
public class ZipUtil { /**
* @param zipFileName
* 生成后得压缩文件目录
* @param inputFile
* 要压缩的目录
* @throws Exception
*/
public static void zip(String zipFileName, File inputFile) throws Exception {
Constant.LOGGER.info("压缩中...");
ZipOutputStream out = new ZipOutputStream(new FileOutputStream(zipFileName));
BufferedOutputStream bo = new BufferedOutputStream(out);
zip(out, inputFile, inputFile.getName(), bo);
bo.close();
out.close(); // 输出流关闭
Constant.LOGGER.info("压缩完成");
} public static void zip(ZipOutputStream out, File f, String base,
BufferedOutputStream bo) throws Exception { // 方法重载
if (f.isDirectory()) {
File[] fl = f.listFiles();
if (fl.length == 0) {
out.putNextEntry(new ZipEntry(base + "/")); // 创建zip压缩进入点base
Constant.LOGGER.info(base + "/");
}
for (int i = 0; i < fl.length; i++) {
zip(out, fl[i], base + "/" + fl[i].getName(), bo); // 递归遍历子文件夹
}
} else {
out.putNextEntry(new ZipEntry(base)); // 创建zip压缩进入点base
Constant.LOGGER.info(base);
FileInputStream in = new FileInputStream(f);
BufferedInputStream bi = new BufferedInputStream(in);
int b;
while ((b = bi.read()) != -1) {
bo.write(b); // 将字节流写入当前zip目录
}
bi.close();
in.close(); // 输入流关闭
}
} public static void zip(String srcPath, String zipPath, String zipFileName)
throws Exception { CheckedOutputStream cos = null;
ZipOutputStream zos = null;
try {
File srcFile = new File(srcPath); // 判断压缩文件保存的路径是否为源文件路径的子文件夹,如果是,则抛出异常(防止无限递归压缩的发生)
if (srcFile.isDirectory() && zipPath.indexOf(srcPath) != -1) {
throw new Exception("压缩文件保存的路径是否为源文件路径的子文件夹");
} // 判断压缩文件保存的路径是否存在,如果不存在,则创建目录
File zipDir = new File(zipPath);
if (!zipDir.exists() || !zipDir.isDirectory()) {
zipDir.mkdirs();
} // 创建压缩文件保存的文件对象
String zipFilePath = zipPath + File.separator + zipFileName;
File zipFile = new File(zipFilePath); cos = new CheckedOutputStream(new FileOutputStream(zipFile),
new CRC32());
zos = new ZipOutputStream(cos); // 如果只是压缩一个文件,则需要截取该文件的父目录
String srcRootDir = srcPath;
if (srcFile.isFile()) {
int index = srcPath.lastIndexOf(File.separator);
if (index != -1) {
srcRootDir = srcPath.substring(0, index);
}
}
// 调用递归压缩方法进行目录或文件压缩
zip(srcRootDir, srcFile, zos);
zos.flush();
} catch (Exception e) {
throw e;
} finally {
try {
if (zos != null) {
zos.close();
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
private static void zip(String srcRootDir, File file, ZipOutputStream zos) throws Exception {
if (file == null) {
return;
} // 如果是文件,则直接压缩该文件
if (file.isFile()) {
int count, bufferLen = 1024;
byte data[] = new byte[bufferLen]; // 获取文件相对于压缩文件夹根目录的子路径
// String subPath = file.getAbsolutePath();
// int index = subPath.indexOf(srcRootDir);
// if (index != -1) {
// subPath = subPath.substring(srcRootDir.length() + File.separator.length());
// }
ZipEntry entry = new ZipEntry(file.getName());
zos.putNextEntry(entry);
BufferedInputStream bis = new BufferedInputStream(new FileInputStream(file));
while ((count = bis.read(data, 0, bufferLen)) != -1) {
zos.write(data, 0, count);
}
bis.close();
zos.closeEntry();
}
// 如果是目录,则压缩整个目录
else {
// 压缩目录中的文件或子目录
File[] childFileList = file.listFiles();
for (int n = 0; n < childFileList.length; n++) {
childFileList[n].getAbsolutePath().indexOf(file.getAbsolutePath());
zip(srcRootDir, childFileList[n], zos);
}
}
} public static void unzip(String zipPath, String targetPath) {
long startTime=System.currentTimeMillis();
try {
ZipInputStream zin=new ZipInputStream(new FileInputStream(zipPath));//输入源zip路径
BufferedInputStream bin=new BufferedInputStream(zin);
File Fout=null;
ZipEntry entry;
try {
while((entry = zin.getNextEntry())!=null && !entry.isDirectory()){
Fout=new File(targetPath,entry.getName());
if(!Fout.exists()){
(new File(Fout.getParent())).mkdirs();
}
FileOutputStream out=new FileOutputStream(Fout);
BufferedOutputStream Bout=new BufferedOutputStream(out);
int b;
while((b=bin.read())!=-1){
Bout.write(b);
}
Bout.close();
out.close();
Constant.LOGGER.info(Fout+"解压成功");
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (bin != null) {
bin.close();
}
} catch (IOException e) {
e.printStackTrace();
}
try {
if (zin != null) {
zin.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
} catch (FileNotFoundException e) {
e.printStackTrace();
}
long endTime=System.currentTimeMillis();
Constant.LOGGER.info("耗费时间: "+(endTime-startTime)+" ms");
} /**
* 测试
*
* @param args
*/
public static void main(String[] args) {
try {
// ZipUtil.zip("G:\\a.zip", new File("G:\\a"));
unzip("G:\\a.zip", "G:\\a");
} catch (Exception e) {
e.printStackTrace();
}
}
}

zip压缩与解压文件夹或文件的更多相关文章

  1. golang zip 压缩,解压(含目录文件)

    每天学习一点go src. 今天学习了zip包的简单使用,实现了含目录的压缩与解压. 写了两个方法,实现了压缩.解压. package ziptest import ( "archive/z ...

  2. 文件操作工具类: 文件/目录的创建、删除、移动、复制、zip压缩与解压.

    FileOperationUtils.java package com.xnl.utils; import java.io.BufferedInputStream; import java.io.Bu ...

  3. 文件压缩、解压工具类。文件压缩格式为zip

    package com.JUtils.file; import java.io.BufferedOutputStream; import java.io.File; import java.io.Fi ...

  4. 正确的 zip 压缩与解压代码

    网上流传的zip压缩与解压 的代码有非常大的问题 尽管使用了ant进行压缩与解压,可是任务的流程还是用的java.util.zip 的方式写的,我在使用的过程中遇到了压缩的文件夹结构有误,甚至出现不同 ...

  5. java zip 压缩与解压

    java zip 压缩与解压 import java.io.BufferedInputStream; import java.io.BufferedOutputStream; import java. ...

  6. Zip 压缩、解压技术在 HTML5 浏览器中的应用

    JSZip 是一款可以创建.读取.修改 .zip 文件的 javaScript 工具.在 web 应用中,免不了需要从 web 服务器中获取资源,如果可以将所有的资源都合并到一个 .zip 文件中,这 ...

  7. golang tar gzip 压缩,解压(含目录文件)

    tar是用于文件归档,gzip用于压缩.仅仅用tar的话,达不到压缩的目的.我们常见的tar.gz就是用gzip压缩生成的tar归档文件. go实现tar压缩与解压与zip类似,区别在于tar需要使用 ...

  8. zip压缩,解压

    //引用 System.IO.Compression.FileSystem.dll var basePath = AppDomain.CurrentDomain.BaseDirectory; Syst ...

  9. C# Zip压缩、解压

    /* *引用 NuGet包 ICSharpCode.SharpZipLib.dll */ public class ZipUtility { /// <summary> /// 所有文件缓 ...

随机推荐

  1. thinkpad x260 U盘进入

    主要有三个问题: 1.bios 不支持U盘启动 联想电脑bios设置u盘启动方法如下:1.打开联想笔记本电脑,在出现开机画面时按F2进入bios设置界面,使用左右方向键将光标移至security菜单, ...

  2. pinctrl框架

    pinctrl框架是linux系统为统一各SOC厂家pin管理,目的是为了减少SOC厂家系统移植工作量. 通常通过设备树初始化pinctrl,并提供调用io接口,以下为全志A64平台的实例: 在dri ...

  3. 常见协议基础知识总结--DHCP协议

    DHCP动态主机配置协议,简单点说,就是提供了自动获取ip地址的功能,基于四层的UDP协议: 以下描述此协议的整个工作流程: (1) 客户端发送discovery报文,二三层广播报文,源ip地址全0: ...

  4. win 7 浏览器被篡改小插曲

    今天下班回家,打开台式机发现IE,火狐都被篡改了.作为运维都会有点强迫症.这是个桌面系统,实在是没兴趣捣鼓.但是还是没办法,经常要用.等我下次有空了,直接换linux好了. 于是开始排查问题吧: 1. ...

  5. django一对多、多对多模型、自关联的建立

    # 原创,转载请留言联系 一对多模型 一对多的关系,例如员工跟部门.一个部门有多个员工.那么在django怎么建立这种表关系呢? 其实就是利用外键,在多的一方,字段指定外键即可.例如员工和部门,员工是 ...

  6. LNMP的基本配置

    LNMP的基本配置cd /usr/local/nginx_php/etc/ > php-fpm.conf                      //清空php-fpm.conf vim ph ...

  7. Django-ContentType

    背景:学位课.专题课.价格策略(每一种课程(学位课和专题课下可分为不同的种类的课程)在不同学习时间内的价格不同) 例如:如何将课程表与价格策略表关联起来: 用外键是可以将课程表和价格策略表关联起来的, ...

  8. JSONObject常用的API

    http://www.cnblogs.com/java-pan/archive/2012/04/07/jsonobject.html 1.介绍基于JSONObject 1.1的API 2.只介绍常用的 ...

  9. ModelMap和ModelAndView区别

    首先介绍ModelMap和ModelAndView的作用 ModelMap ModelMap对象主要用于传递控制方法处理数据到结果页面,也就是说我们把结果页面上需要的数据放到ModelMap对象中即可 ...

  10. C#在 64位系统下出现 “未能加载文件或程序集”错误

    64位系统下,Build的时候,如果选择Any CPU,默认会按照64位进行编译,便无法加载某些旧的dll,这些dll可能是特定到X86 CPU的. 所以,把编译选项中改为 X86CPU,就可以运行了 ...