原文:http://www.open-open.com/code/view/1430906539866

package com.topsoft.websites.utils;

import java.io.*;
import java.util.logging.Logger;
import java.util.zip.*; /**
* Created by sunyameng on 14-3-10.
*/
public class ZipUtil {
private final static Logger logger = Logger.getLogger(ZipUtil.class.getName());
private static final int BUFFER = 1024 * 10;
/**
* 将指定目录压缩到和该目录同名的zip文件,自定义压缩路径
*
* @param sourceFilePath 目标文件路径
* @param zipFilePath 指定zip文件路径
* @return
*/
public static boolean zip(String sourceFilePath, String zipFilePath,String zipFileName) {
boolean result = false;
File source = new File(sourceFilePath);
if (!source.exists()) {
logger.info(sourceFilePath + " doesn't exist.");
return result;
}
if (!source.isDirectory()) {
logger.info(sourceFilePath + " is not a directory.");
return result;
}
File zipFile = new File(zipFilePath + File.separator + zipFileName + ".zip");
if (zipFile.exists()) {
logger.info(zipFile.getName() + " is already exist.");
return result;
} else {
if (!zipFile.getParentFile().exists()) {
if (!zipFile.getParentFile().mkdirs()) {
logger.info("cann't create file " + zipFileName);
return result;
}
}
}
logger.info("creating zip file...");
FileOutputStream dest = null;
ZipOutputStream out = null;
try {
dest = new FileOutputStream(zipFile);
CheckedOutputStream checksum = new CheckedOutputStream(dest, new Adler32());
out = new ZipOutputStream(new BufferedOutputStream(checksum));
out.setMethod(ZipOutputStream.DEFLATED);
compress(source, out, source.getName());
result = true;
} catch (FileNotFoundException e) {
e.printStackTrace();
} finally {
if (out != null) {
try {
out.closeEntry();
} catch (IOException e) {
e.printStackTrace();
}
try {
out.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
if (result) {
logger.info("done.");
} else {
logger.info("fail.");
}
return result;
} private static void compress(File file, ZipOutputStream out, String mainFileName) {
int index = file.getAbsolutePath().indexOf(mainFileName);
String entryName = file.getAbsolutePath().substring(index);
//System.out.println(entryName);
if (file.isFile()) {
FileInputStream fi = null;
BufferedInputStream origin = null;
try {
fi = new FileInputStream(file);
origin = new BufferedInputStream(fi, BUFFER);
ZipEntry entry = new ZipEntry(entryName);
out.putNextEntry(entry);
byte[] data = new byte[BUFFER];
int count;
while ((count = origin.read(data, 0, BUFFER)) != -1) {
out.write(data, 0, count);
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
if (origin != null) {
try {
origin.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
} else if (file.isDirectory()) {
try {
out.putNextEntry(new ZipEntry(entryName+File.separator));
} catch (IOException e) {
e.printStackTrace();
}
File[] fs = file.listFiles();
if (fs != null && fs.length > 0) {
for (File f : fs) {
compress(f, out, mainFileName);
}
}
}
} /**
* 将zip文件解压到指定的目录,该zip文件必须是使用该类的zip方法压缩的文件
*
* @param zipFile 要解压的zip文件
* @param destPath 指定解压到的目录
* @return
*/
public static boolean unzip(File zipFile, String destPath) {
boolean result = false;
if (!zipFile.exists()) {
logger.info(zipFile.getName() + " doesn't exist.");
return result;
}
File target = new File(destPath);
if (!target.exists()) {
if (!target.mkdirs()) {
logger.info("cann't create file " + target.getName());
return result;
}
}
String mainFileName = zipFile.getName().replace(".zip", "");
File targetFile = new File(destPath + File.separator + mainFileName);
if (targetFile.exists()) {
logger.info(targetFile.getName() + " already exist.");
return result;
}
ZipInputStream zis = null;
logger.info("start unzip file ...");
try {
FileInputStream fis = new FileInputStream(zipFile);
CheckedInputStream checksum = new CheckedInputStream(fis, new Adler32());
zis = new ZipInputStream(new BufferedInputStream(checksum));
ZipEntry entry;
while ((entry = zis.getNextEntry()) != null) {
int count;
byte data[] = new byte[BUFFER];
String entryName = entry.getName();
//logger.info(entryName);
String newEntryName = destPath + File.separator + entryName;
newEntryName=newEntryName.replaceAll("\\\\", "/");
File f = new File(newEntryName);
if(newEntryName.endsWith("/")){
if(!f.exists()){
if(!f.mkdirs()) {
throw new RuntimeException("can't create directory " + f.getName());
}
}
}else{
File temp=f.getParentFile();
if (!temp.exists()) {
if (!temp.mkdirs()) {
throw new RuntimeException("create file " + temp.getName() + " fail");
}
}
FileOutputStream fos = new FileOutputStream(f);
BufferedOutputStream dest = new BufferedOutputStream(fos, BUFFER);
while ((count = zis.read(data, 0, BUFFER)) != -1) {
dest.write(data, 0, count);
}
dest.flush();
dest.close();
}
}
result = true;
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
if (zis != null) {
try {
zis.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
if (result) {
logger.info("done.");
} else {
logger.info("fail.");
}
return result;
} public static void main(String[] args) throws IOException {
// String path="D:\\temp\\B";
// ZipUtil.zip(path,"d:/temp/c","anhuigs123");
String zipfile ="D:\\temp\\c\\B.zip";
File zipFile = new File(zipfile);
String output="D:\\temp\\c";
ZipUtil.unzip(zipFile, output);
}
}

java zip 工具类的更多相关文章

  1. java zip工具类

    依赖jar :apache-ant-1.9.2-bin.zip import java.io.File; import java.io.FileInputStream; import java.io. ...

  2. java常用工具类(二)

    1.FtpUtil package com.itjh.javaUtil; import java.io.File; import java.io.FileOutputStream; import ja ...

  3. Java Properties工具类详解

    1.Java Properties工具类位于java.util.Properties,该工具类的使用极其简单方便.首先该类是继承自 Hashtable<Object,Object> 这就奠 ...

  4. Java json工具类,jackson工具类,ObjectMapper工具类

    Java json工具类,jackson工具类,ObjectMapper工具类 >>>>>>>>>>>>>>> ...

  5. Java日期工具类,Java时间工具类,Java时间格式化

    Java日期工具类,Java时间工具类,Java时间格式化 >>>>>>>>>>>>>>>>>&g ...

  6. Java并发工具类 - CountDownLatch

    Java并发工具类 - CountDownLatch 1.简介 CountDownLatch是Java1.5之后引入的Java并发工具类,放在java.util.concurrent包下面 http: ...

  7. MinerUtil.java 爬虫工具类

    MinerUtil.java 爬虫工具类 package com.iteye.injavawetrust.miner; import java.io.File; import java.io.File ...

  8. MinerDB.java 数据库工具类

    MinerDB.java 数据库工具类 package com.iteye.injavawetrust.miner; import java.sql.Connection; import java.s ...

  9. 小记Java时间工具类

    小记Java时间工具类 废话不多说,这里主要记录以下几个工具 两个时间只差(Data) 获取时间的格式 格式化时间 返回String 两个时间只差(String) 获取两个时间之间的日期.月份.年份 ...

随机推荐

  1. Windows 10 Mac 为Vs Code配置C/C++环境

    2019-06-10 更新: 加上Mac版本的Vscode配置文件 0.前言 实现效果:右键一键编译运行C/C++文件 Vs code的代码效果很好看,也很轻量,所以想为Vs Code配置C/C++环 ...

  2. GIMP里的Path移动,旋转,翻转操作

    1/Path的移动: 快捷键Ctrl+Move Tool 2/Path的旋转: 选择Rotate Tool,在Path中选择,出现十字圈. Angel下的滑块调节一定的角度,在合适的位置即可. 3/P ...

  3. CVS在update时状态status

    cvs update -Ad 时,terminal 会display如下: P xx.v P xx.c ? xx.v ? xx.c A xx.v M xx.v U xx.v C xx.v 第一个字母: ...

  4. perl中foreach(二)

    本文和大家重点讨论一下Perl foreach命令的用法,Perl foreach循环中控制变量的值会被Perl自动保存和恢复.当循环进行时,是没有办法改变其值的.循环结束时,变量的值会回到循环开始前 ...

  5. Beautiful Soup 4.2.0 doc_tag、Name、Attributes、多值属性

    找到了bs4的中文文档,对昨天爬虫程序里所涉及的bs4库进行学习.这篇代码涉及到tag.Name.Attributes以及多值属性. ''' 对象的种类 Beautiful Soup将复杂HTML文档 ...

  6. MySQL学习点滴

    MySQL学习点滴 --分区表 概述: 分区功能并不是在存储引擎层完成的,因此很多存储引擎包括InnoDB, MyISAM, NDB等都支持分区功能.但也并不是所有的存储引擎都支持分区.在使用分区前, ...

  7. PAT Basic 1027

    1027 打印沙漏 本题要求你写个程序把给定的符号打印成沙漏的形状.例如给定17个“*”,要求按下列格式打印 ***** *** * *** ***** 所谓“沙漏形状”,是指每行输出奇数个符号:各行 ...

  8. django的rest framework框架——分页、视图、路由、渲染器

    一.rest framework的分页 1.使用rest framework内置类PageNumberPagination实现分类 from django.conf.urls import url f ...

  9. angularJs模块ui-router之多视图

    可以给ui-view指定名称,这样一个模板中就可以有多个ui-view.假设您有一个应用,需要动态填充graph.table data和filters,像下面这样: 当您需要使用多视图时,需要用到状态 ...

  10. SPOJ DIVSUM - Divisor Summation

    DIVSUM - Divisor Summation #number-theory Given a natural number n (1 <= n <= 500000), please ...