1.压缩文件或整个目录

// ZipCompression.java

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;

public class ZipCompression {

private String mFileDest;
 private ZipOutputStream mZipOutputStream;
 private static final String SEPARATOR = File.separator;

// public static void main(String[] args) {
 //
 // // ZipCompress zipCompress = new ZipCompress("E:\\1.zip");
 // ZipCompression zip = new ZipCompression("1.zip");
 // zip.add("1.txt");
 // zip.add(".");
 // zip.add("2.txt");
 // zip.close();
 // }

/**
  * @param pathname
  *            zip目标文件的名字
  */
 public ZipCompression(String pathname) {
  mFileDest = new File(pathname).getAbsolutePath();

FileOutputStream fos;
  try {
   fos = new FileOutputStream(mFileDest, true);
   mZipOutputStream = new ZipOutputStream(fos);
  } catch (FileNotFoundException e) {
   printStackTrace(e);
  }
 }

/**
  * 关闭zip文件,结束打包.
  */
 public void close() {
  if (mZipOutputStream != null) {
   try {
    mZipOutputStream.close();
   } catch (IOException e) {
    printStackTrace(e);
   }
   mZipOutputStream = null;
  }
 }

/**
  * 添加一个文件或目录到zip文件
  *
  * @param filePath
  *            待压缩的文件或目录,可以是相对目录
  */
 public void add(String filePath) {

try {
   File file = new File(filePath);
   String path = "";
   if (file.isDirectory()) {
    filePath = file.getAbsolutePath();
    if (filePath.endsWith("."))
     filePath = filePath.substring(0, filePath.length() - 1);
    if (filePath.endsWith(SEPARATOR))
     filePath = filePath.substring(0, filePath.length() - 1);
    // System.out.println("filePath:" + filePath);

int pos = filePath.lastIndexOf(SEPARATOR);
    // System.out.println(filePath.substring(0, pos));
    if (filePath.substring(0, pos).contains(SEPARATOR))
     path = filePath.substring(pos + 1, filePath.length())
       + SEPARATOR;
    // System.out.println("path:" + path);
   }

byte[] buffer = new byte[1024];
   add(mZipOutputStream, path, filePath, buffer);
  } catch (Exception e) {
   printStackTrace(e);
  }
 }

/**
  * 添加一个文件或目录到zip文件,如果是目录则递归打包子目录
  *
  * @param zos
  *            zip压缩的目标文件
  * @param path
  *            待创建的zip文件夹内的相内路径
  * @param file
  *            待压缩的文件或目录的路径
  * @param buffer
  *            数据临时缓冲区
  */
 private void add(ZipOutputStream zos, String path, String file,
   byte[] buffer) {

try {
   File inputFile = new File(file);
   if (inputFile.isFile()) {
    add(zos, path, inputFile, buffer);
   } else if (inputFile.isDirectory()) {
    // System.out.println("add dir:" + inputFile.getName());

for (File subFile : inputFile.listFiles()) {
     if (subFile.isDirectory()) {
      String newPath = path + subFile.getName() + SEPARATOR;
      add(zos, newPath, subFile.getPath(), buffer);
     } else {
      add(zos, path, subFile, buffer);
     }
    }
   }
  } catch (Exception e) {
   printStackTrace(e);
  }
 }

/**
  * 添加一个已打开的文件到zip中
  *
  * @param zos
  *            zip压缩的目标文件
  * @param path
  *            待创建的zip文件夹内的相内路径
  * @param file
  *            待压缩的文件
  * @param buffer
  *            数据临时缓冲区
  */
 private void add(ZipOutputStream zos, String path, File file, byte[] buffer) {
  FileInputStream fis = null;
  try {

path.equalsIgnoreCase("");
   // 防止将目标zip文件打包进自己的压缩包内
   String src = file.getAbsolutePath();
   // System.out.println("src:" + src);
   if (mFileDest.equalsIgnoreCase(src)) {
    // System.out.println("Error! It's dest file! " + src);
    return;
   }

int ret;
   try {
    ZipEntry zipEntry = new ZipEntry(path + file.getName());
    zos.putNextEntry(zipEntry);
    FileInputStream fin = new FileInputStream(file);
    while ((ret = fin.read(buffer)) != -1) {
     zos.write(buffer, 0, ret);
    }
    fin.close();
    zos.closeEntry();
   } catch (Exception e) {
    printStackTrace(e);
   }

} catch (Exception e) {
   printStackTrace(e);
  } finally {
   try {
    if (fis != null)
     fis.close();
   } catch (IOException e) {
    printStackTrace(e);
   }
  }
 }

private void printStackTrace(Exception exception) {
  StringWriter sw = new StringWriter();
  PrintWriter pw = new PrintWriter(sw);
  exception.printStackTrace(pw);
  System.out.print(sw.toString());

// e.printStackTrace();
 }
}

2.解压一个zip文件到指定的目录

// ZipDecompression.java

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.util.Enumeration;
import java.util.zip.ZipEntry;
import java.util.zip.ZipFile;

public class ZipDecompression {

private final String mZipFile;
 private final String mDestPath;

public static void main(String[] args) {
  ZipDecompression unzip = new ZipDecompression("e:\\2.zip", "E:\\2\\");
  unzip.start();
 }

public ZipDecompression(String zip, String destPath) {
  mZipFile = zip;
  mDestPath = destPath;
 }

/**
  * 开始解压缩zip
  *
  * @return 成功返回true,出现任何错误返回false
  */
 public boolean start() {
  byte[] buffer = new byte[1024];
  int ret = 0;
  try {
   ZipFile zipFile = new ZipFile(mZipFile);
   Enumeration<? extends ZipEntry> entries = zipFile.entries();
   ZipEntry entry;
   String name;
   InputStream fis;
   FileOutputStream fos;
   while (entries.hasMoreElements()) {
    entry = entries.nextElement();

name = mDestPath + entry.getName();
    name = name.replaceAll("\\*", "/"); // 替换会出现不成功!
    // System.out.println("\n" + name);
    mkdirs(name);

fos = new FileOutputStream(name);
    fis = zipFile.getInputStream(entry);
    do {
     ret = fis.read(buffer);
     if (ret == -1)
      break;
     fos.write(buffer, 0, ret);
    } while (true);
    fis.close();
    fos.close();
   }
  } catch (FileNotFoundException e) {
   printStackTrace(e);
   return false;
  } catch (IOException e) {
   printStackTrace(e);
   return false;
  } catch (Exception e) {
   printStackTrace(e);
   return false;
  }
  return true;
 }

/**
  * 递归创建目录
  *
  * @param pathname
  *            文件或目录名称
  */
 private void mkdirs(String pathname) {

try {
   File file = new File(pathname);
   if (!file.isDirectory()) {
    for (int i = pathname.length() - 1; i >= 0; i--) {
     Character c = pathname.charAt(i);
     if (c.equals('\\') || c.equals('/')) {
      String newPath = pathname.substring(0, i);
      // System.out.println(newPath);
      file = new File(newPath);
      break;
     }
    }
   }
   if (!file.exists())
    file.mkdirs();
  } catch (Exception e) {
   printStackTrace(e);
  }
 }

private static void printStackTrace(Exception exception) {
  StringWriter sw = new StringWriter();
  PrintWriter pw = new PrintWriter(sw);
  exception.printStackTrace(pw);
  System.out.print(sw.toString());

// e.printStackTrace();
 }
}

Java Zip压缩的更多相关文章

  1. java ZIP压缩文件

    问题描述:     使用java ZIP压缩文件和目录 问题解决:     (1)单个文件压缩 注:     以上是实现单个文件写入压缩包的代码,注意其中主要是在ZipOutStream流对象中创建Z ...

  2. java zip 压缩文件

    zip压缩:ZipOutputStream.ZipFile.ZipInputStream 三个类的作用 一段 java  zip  压缩的代码: File dir = new File("C ...

  3. java zip 压缩与解压

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

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

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

  5. Java Zip压缩实现

    最近在自学javaWeb,先复习一下java,把还给老师的东西再找回来(知识如果不用很快就会忘记啊).. 今天看到了zip压缩,决定要整理一下. java将有关zip压缩的内容都封装在java.uti ...

  6. Java zip 压缩 文件夹删除,移动,重命名,复制

    FileUtil.java import java.io.*; import java.util.List; import java.util.zip.ZipEntry; import java.ut ...

  7. Java ZIP压缩和解压缩文件并兼容linux

    JDK中自带的ZipOutputStream在压缩文件时,如果文件名中有中文,则压缩后的 zip文件打开时发现中文文件名变成乱码. 解决的方法是使用apache-ant-zip.jar包(见附件)中的 ...

  8. java zip压缩优化版 解决压缩后文件一直被占用无法删除

    最近进行zip操作,从网上找到一个处理方法,但是经过试验存在一些bug,主要是文件流的申明存在问题,导致jvm一直占用文件而不释放,特意把自己修改的发出来,已备记录 import java.io.Bu ...

  9. java zip压缩文件和文件夹

    public class FileUtil { /** * 压缩文件-File * @param out zip流 * @param srcFiles 要压缩的文件 * @param path 相对路 ...

随机推荐

  1. C struct中的位域 bitfield

    C struct中的位域 bitfield 结构体的成员可以限制其位域,每个成员可以使用用比字节还小的取值范围,下面的结构体s1中,四个成员每个成员都是2bit的值(0~3),整个结构体占据的空间依然 ...

  2. 5.安装hbase

    下载安装包并解压设置hbase环境变量配置hbase-site.xml启动hbase检测hbase启动情况测试hbase shell 下载安装包并解压 https://mirrors.tuna.tsi ...

  3. rsync+inotify实现实时同步,自动触发同步文件

    本文参考来自:http://chocolee.blog.51cto.com/8158455/1400596 我的需求和他的略有不同,同时做了一下更改,如下: 需求:两台机器相互为主备,搭建相同的两个服 ...

  4. OJ错误命令解释

    ①Presentation Error (PE) : 虽然您的程序貌似输出了正确的结果,但是这个结果的格式有点问题. 请检查程序的输出是否多了或者少了空格(' ').制表符('\t')或者换行符('\ ...

  5. TCP系列01—概述及协议头格式

    一.TCP简单介绍 我们经常听人说TCP是一个面向连接的(connection-oriented).可靠的(reliable).字节流式(byte stream)传输协议,  TCP的这三个特性该怎么 ...

  6. 软工网络15团队作业4——Alpha阶段敏捷冲刺-4

    一.当天站立式会议照片: 二.项目进展 昨天已完成的工作: 完成程序副界面的设计与信息的输入统计 明天计划完成的工作: 日期等细致信息的处理 工作中遇到的困难: 对微信小程序开发的代码构成有了一些了解 ...

  7. vue服务端渲染axios预取数据

    首先是要参考vue服务端渲染教程:https://ssr.vuejs.org/zh/data.html. 本文主要代码均参考教程得来.基本原理如下,拷贝的原文教程. 为了解决这个问题,获取的数据需要位 ...

  8. python 爬虫每天定时启动爬虫任务

     # coding=utf-8 import datetime import time def doSth(): # 这里是执行爬虫的main程序     print '爬虫要开始运转了....'   ...

  9. Runtime介绍

    本文目录 1.Runtime简介 2.Runtime相关的头文件 3.技术点和应用场景 3_1.获取属性\成员变量列表 3_2.交换方法实现 3_3.类\对象的关联对象,假属性 3_4.动态添加方法, ...

  10. NOI 97 (Vijos 1464)积木游戏(DP)

    很普通的DP,设dp[i][j][k]为第i块积木放在第j堆且摆放状态为k的最高高度.方程很容易推出. # include <cstdio> # include <cstring&g ...