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. Ducci序列 (Ducci Sequence,ACM/ICPC Seoul 2009,UVa1594)

    题目描述: 题目思路: 直接模拟 #include<stdio.h> #include<string.h> #define maxn 105 int less(const ch ...

  2. [HNOI2018]寻宝游戏(题解转载自别处)

    题解(自别处转载): Luogu CSDN 这题关键是将运算符也替换成0,1 然后在运算符与原串混杂里找规律. 而且替换的方式也有所要求,考场上两种替换方式都要尝试. #include <bit ...

  3. 完全背包问题 :背包dp

    题目描述: 有 N种物品和一个容量是 V 的背包,每种物品都有无限件可用.第 i 种物品的体积是 vi,价值是 wi. 求解将哪些物品装入背包,可使这些物品的总体积不超过背包容量,且总价值最大.输出最 ...

  4. SpringCloud IDEA 教学 (二) Eureka Service

    写在开头 本篇继续介绍基于Eureka的SpringCloud微服务搭建,回顾一下搭建过程, 第一步:建立一个服务注册中心: 第二步:建立微服务并注入到注册中心: 第三步:建立client端来访问微服 ...

  5. python函数中的位置参数、默认参数、关键字参数、可变参数区别

    一.位置参数 调用函数时根据函数定义的参数位置来传递参数. #!/usr/bin/env python # coding=utf-8 def print_hello(name, sex): sex_d ...

  6. UVALive - 6872 Restaurant Ratings 数位dp

    题目链接: http://acm.hust.edu.cn/vjudge/problem/113727 Restaurant Ratings Time Limit: 3000MS 题意 给你一个长度为n ...

  7. LintCode-38.搜索二维矩阵 II

    搜索二维矩阵 II 写出一个高效的算法来搜索m×n矩阵中的值,返回这个值出现的次数. 这个矩阵具有以下特性: 每行中的整数从左到右是排序的. 每一列的整数从上到下是排序的. 在每一行或每一列中没有重复 ...

  8. 理解windows模型

    同步 所谓同步,就是在发出一个功能调用时,在没有得到结果之前,该调用就不返回.按照这个定义,其实绝大多数函数都是同步调用(例如sin, isdigit等).但是一般而言,我们在说同步.异步的时候,特指 ...

  9. JavaScript数组自定义属性

    我们可以以json键值对的形式自定义属性. 首先定义一个JS数组JSarray. 然后按json键值对的形式进行赋值. 最后在控制台显示结果. 代码如下: var JSarray = new Arra ...

  10. 3dContactPointAnnotationTool开发日志(十四)

      貌似每次让用户手动输入文件路径太不人道了,于是参考Unity 实用教程 之 调用系统窗口选择文件或路径增加了让用户浏览文件的功能,点击输入框旁边的+就可以找到文件并加载进来:   貌似调整位置再计 ...