Java对zip格式压缩和解压缩

通过使用java的相关类可以实现对文件或文件夹的压缩,以及对压缩文件的解压。

1.1 ZIP和GZIP的区别

gzip是一种文件压缩工具(或该压缩工具产生的压缩文件格式),它的设计目标是处理单个的文件。gzip在压缩文件中的数据时使用的就是zlib。为了保存与文件属性有关的信息,gzip需要在压缩文件(*.gz)中保存更多的头信息内容,而zlib不用考虑这一点。但gzip只适用于单个文件,所以我们在UNIX/Linux上经常看到的压缩包后缀都是*.tar.gz或*.tgz,也就是先用tar把多个文件打包成单个文件,再用gzip压缩的结果。
     zip只是一种数据结构,跟rar同类型。zip是适用于压缩多个文件的格式(相应的工具有PkZip和WinZip等),因此,zip文件还要进一步包含文件目录结构的信息,比gzip的头信息更多。但需要注意,zip格式可采用多种压缩算法,我们常见的zip文件大多不是用zlib的算法压缩的,其压缩数据的格式与gzip大不一样。

1.2相关类与接口:

Checksum 接口:表示数据校验和的接口,被类Adler32和CRC32实现
Adler32 :使用Alder32算法来计算Checksum数目
CRC32 :使用CRC32算法来计算Checksum数目

CheckedInputStream :InputStream派生类,可得到输入流的校验和Checksum,用于校验数据的完整性
CheckedOutputStream :OutputStream派生类,可得到输出流的校验Checksum, 用于校验数据的完整性

DeflaterOutputStream :压缩类的基类。
ZipOutputStream :DeflaterOutputStream的一个子类,把数据压缩成Zip文件格式
GZIPOutputStream :DeflaterOutputStream的一个子类,把数据压缩成GZip文件格式

InflaterInputStream :解压缩类的基类
ZipInputStream :InflaterInputStream的一个子类,能解压缩Zip格式的数据
GZIPInputStream :InflaterInputStream的一个子类,能解压缩Zip格式的数据

ZipEntry 类:表示 ZIP 文件条目
ZipFile 类:此类用于从 ZIP 文件读取条目

1.3 压缩文件

下面实例我们使用了apache的zip工具包(所在包为ant.jar ),因为java类型自带的不支持中文路径,不过两者使用的方式是一样的,只是apache压缩工具多了设置编码方式的接口,其他基本上是一样的。另外,如果使用org.apache.tools.zip.ZipOutputStream来压缩的话,我们只能使用org.apache.tools.zip.ZipEntry来解压,而不能使用java.util.zip.ZipInputStream来解压读取了,当然apache并未提供ZipInputStream类。

public
static
void compress(String srcFilePath, String destFilePath) {

File src = new File(srcFilePath);

if (!src.exists()) {

throw
new RuntimeException(srcFilePath + "不存在");

}

File zipFile = new File(destFilePath);

try {

FileOutputStream fos = new FileOutputStream(zipFile);

            CheckedOutputStream cos = new CheckedOutputStream(fos, new CRC32());

            ZipOutputStream zos = new ZipOutputStream(cos);

            String baseDir = "";

            compressbyType(src, zos, baseDir);

zos.close();

} catch (Exception e) {

// TODO Auto-generated catch block

e.printStackTrace();

}

}

private
static
void compressbyType(File src, ZipOutputStream zos,

String baseDir) {

if (!src.exists())

return;

System.out.println("压缩" + baseDir + src.getName());

if (src.isFile()) {

compressFile(src, zos, baseDir);

} else
if (src.isDirectory()) {

compressDir(src, zos, baseDir);

}

}

/**

* 压缩文件

*

*/

private
static
void compressFile(File file, ZipOutputStream zos,

String baseDir) {

if (!file.exists())

return;

try {

BufferedInputStream bis = new BufferedInputStream(

                    new FileInputStream(file));

            ZipEntry entry = new ZipEntry(baseDir + file.getName());

            zos.putNextEntry(entry);

            int count;

            byte[] buf = new byte[BUFSIZE];

            while ((count = bis.read(buf)) != -1) {

                zos.write(buf, 0, count);

            }

bis.close();

} catch (Exception e) {

// TODO: handle exception

}

}

/**

* 压缩文件夹

*

*/

private
static
void compressDir(File dir, ZipOutputStream zos,

String baseDir) {

if (!dir.exists())

return;

File[] files = dir.listFiles();

if(files.length == 0){

            try {

                zos.putNextEntry(new ZipEntry(baseDir + dir.getName()

                        + File.separator));

            } catch (IOException e) {

                e.printStackTrace();

            }

            

        }

for (File file : files) {

compressbyType(file, zos, baseDir + dir.getName() + File.separator);

}

}

总结步骤:

  1. 创建压缩到的文件File zipFile = new File(destFilePath);
  2. 根据zipFile生成ZipOutputStream用于写入即将被压缩的文件

    FileOutputStream fos = new FileOutputStream(zipFile);

    CheckedOutputStream cos = new                                      CheckedOutputStream(fos, new CRC32());

    ZipOutputStream zos = new ZipOutputStream(cos);

  3. 循环遍历源文件,首先需要创建ZipEntry用于标记压缩文件中含有的条目

    ZipEntry entry = new ZipEntry(baseDir + file.getName());

    然后将条目增加到ZipOutputStream中,

    zos.putNextEntry(entry);

    最后再调用要写入条目对应文件的输入流读取文件内容写入到压缩文件中。

    BufferedInputStream bis = new BufferedInputStream(

            new FileInputStream(file));

            ZipEntry entry = new ZipEntry(baseDir + file.getName());

            zos.putNextEntry(entry);

            int count;

            byte[] buf = new byte[BUFSIZE];

            while ((count = bis.read(buf)) != -1) {

                zos.write(buf, 0, count);

            }

    注意:如果是空目录直接zos.putNextEntry(new ZipEntry(baseDir +     dir.getName()+ File.separator))并不用写入文件内容,其中最主要的涉及到目录的压缩的,就是这一句话  out.putNextEntry(new ZipEntry(base + "/")); //放入一级目录 (防止空目录被丢弃)

    1.4 解压zip文件

    public
    static
    void decompress(String srcPath, String dest) throws Exception {

    File file = new File(srcPath);

    if (!file.exists()) {

    throw
    new RuntimeException(srcPath + "所指文件不存在");

    }

    ZipFile zf = new ZipFile(file);

    Enumeration
    entries = zf.getEntries();

    ZipEntry
    entry = null;

    while (entries.hasMoreElements()) {

    entry = (ZipEntry) entries.nextElement();

    System.out.println("解压" + entry.getName());

    if (entry.isDirectory()) {

    String dirPath = dest + File.separator + entry.getName();

    File dir = new File(dirPath);

    dir.mkdirs();

    } else {

    // 表示文件

    File f = new File(dest + File.separator + entry.getName());

    if (!f.exists()) {

    String dirs = FileUtils.getParentPath(f);

    File parentDir = new File(dirs);

    parentDir.mkdirs();

    }

    f.createNewFile();

    // 将压缩文件内容写入到这个文件中

    InputStream is = zf.getInputStream(entry);

    FileOutputStream fos = new FileOutputStream(f);

    int
    count;

    byte[] buf = new
    byte[8192];

    while ((count = is.read(buf)) != -1) {

    fos.write(buf, 0, count);

    }

    is.close();

    fos.close();

    }

    }

    }

Java对zip格式压缩和解压缩的更多相关文章

  1. Java用ZIP格式压缩和解压缩文件

    转载:java jdk实例宝典 感觉讲的非常好就转载在这保存! java.util.zip包实现了Zip格式相关的类库,使用格式zip格式压缩和解压缩文件的时候,须要导入该包. 使用zipoutput ...

  2. Java 的zip压缩和解压缩

    Java 的zip压缩和解压缩 好久没有来这写东西了,今天中秋节,有个东西想拿出来分享,一来是工作中遇到的问题,一来是和csdn问候一下,下面就分享一个Java中的zip压缩技术,代码实现比较简单,代 ...

  3. [Java 基础] 使用java.util.zip包压缩和解压缩文件

    reference :  http://www.open-open.com/lib/view/open1381641653833.html Java API中的import java.util.zip ...

  4. java采用zip方式实现String的压缩和解压缩CompressStringUtil类

    CompressStringUtil类:不多说,直接贴代码: /** * 压缩 * * @param paramString * @return */ public static final byte ...

  5. Java ZIP压缩和解压缩文件(解决中文文件名乱码问题)

    Java ZIP压缩和解压缩文件(解决中文文件名乱码问题) 学习了:http://www.tuicool.com/articles/V7BBvy 引用原文: JDK中自带的ZipOutputStrea ...

  6. 使用commons-compress操作zip文件(压缩和解压缩)

    http://www.cnblogs.com/luxh/archive/2012/06/28/2568758.html Apache Commons Compress是一个压缩.解压缩文件的类库. 可 ...

  7. Linux常用命令学习3---(文件的压缩和解压缩命令zip unzip tar、关机和重启命令shutdown reboot……)

    1.压缩和解压缩命令    常用压缩格式:.zip..gz..bz2..tar.gz..tar.bz2..rar .zip格式压缩和解压缩命令        zip 压缩文件名 源文件:压缩文件   ...

  8. IO操作之使用zip包压缩和解压缩文件

    转自:http://www.cdtarena.com/java.html​​Java API中的import java.util.zip.*;包下包含了Java对于压缩文件的所有相关操作. 我们可以使 ...

  9. java工具类——java将一串数据按照gzip方式压缩和解压缩

    我要整理在工作中用到的工具类分享出来,也方便自己以后查阅使用,这些工具类都是我自己实际工作中使用的 import java.io.ByteArrayInputStream; import java.i ...

随机推荐

  1. Android-openFileInput openFileOutput

    Android设计了一套可以操作自身APP目录文件对API openFileInput openFileOutput,读取只需传入文件名,写入需要传入文件名 与 权限模式 界面: 布局代码: < ...

  2. xml和JSON格式相互转换的Java实现

    依赖的包: json-lib-2.4-jdk15.jar ezmorph-1.0.6.jar xom-1.2.1.jar commons-lang-2.1.jar commons-io-1.3.2.j ...

  3. ceph pg_num 数值计算

    通常在创建pool之前,需要覆盖默认的pg_num,官方推荐: 若少于5个OSD, 设置pg_num为128. 5~10个OSD,设置pg_num为512. 10~50个OSD,设置pg_num为40 ...

  4. OpenStack 业务链networking-sfc介绍 (2) - 底层原理

    原文链接:https://blog.csdn.net/bc_vnetwork/article/details/65630475 1.  SFC底层实现原理 port chain和ovs driver/ ...

  5. 在Ubuntu16.04里面安装Gogland!

    一,安装 把linux版本的Gogland拷贝到Ubuntu16.04里面,随后在想要存放它的地方解压缩,这样就完成了安装! 二,让Gogland可以快速启动 linux版本的Gogland的启动是用 ...

  6. java学习笔记—Servlet技术(11)

    如果大家要开发一个动态的网站,那么就必须要学习一种动态的网页开发技术.那么在SUN提供的JavaEE中主要包含两种开发动态网页的技术:Servlet和JSP技术. Servlet技术简介 Servle ...

  7. leecode刷题(20)-- 删除链表中的节点

    leecode刷题(20)-- 删除链表中的节点 删除链表中的节点 描述: 请编写一个函数,使其可以删除某个链表中给定的(非末尾)节点,你将只被给定要求被删除的节点. 现有一个链表 -- head = ...

  8. 【bzoj4998】星球联盟(并查集+边双)

    题面 传送门 题解 总算有自己的\(bzoj\)账号啦! 话说这题好像\(Scape\)去年暑假就讲过--然而我到现在才会-- \(LCT\)什么的跑得太慢了而且我也不会,所以这里是一个并查集的做法 ...

  9. 【bash】今天你坑队友了吗

    需求: 压缩日志并删除压缩过的文件 很日常的运维需求!!! 好,来看代码 echo 'start' quke.log rm -f quke.log echo 'delete' 不管是初级运维还是高级运 ...

  10. Laravel 的核心概念

    工欲善其事,必先利其器.在开发Xblog的过程中,稍微领悟了一点Laravel的思想.确实如此,这篇文章读完你可能并不能从无到有写出一个博客,但知道Laravel的核心概念之后,当你再次写起Larav ...