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. oracle 学习随笔一: 字段大小写

    字段上加大小写:"reportId"  即可

  2. springMVC第二章

    springMVC第二章 一.URL 映射 可以同时设置多个URL来访问某个控制器或方法.设置value属性: @RequestMapping(value= {"/grade",& ...

  3. Windows下PHP安全环境的搭建

    笔者一直在Windows环境下搭建PHP的运行环境,大大小小的运行环境用过不少,从开始的WAMP到后来的XAMPP以及PHPnow.WAMP和XAMPP都是继承mysql apache以及PHP库的运 ...

  4. 提升方法-AdaBoost

    提升方法通过改变训练样本的权重,学习多个分类器(弱分类器/基分类器)并将这些分类器进行线性组合,提高分类的性能. AdaBoost算法的特点是不改变所给的训练数据,而不断改变训练数据权值的分布,使得训 ...

  5. Sum of Consecutive Prime Numbers(素数打表+尺取)

    Description Some positive integers can be represented by a sum of one or more consecutive prime numb ...

  6. 《软件工程实践》第五次作业-WordCount进阶需求 (结对第二次)

    在文章开头给出结对同学的博客链接.本作业博客的链接.你所Fork的同名仓库的Github项目地址 本作业博客链接 github pair c 031602136魏璐炜博客 031602139徐明盛博客 ...

  7. javaIO--字符流

    java提供字符流对自否刘式文件进行数据读写操作.字符输入流类是Reader及其子类,输出流是Writer及其子类. 另外,上一篇javaIO写的是字节流,字节流方式也可以对以字符为基本类型的流式文件 ...

  8. iOS-根据两个经纬度计算相距距离

    CLLocation *orig=[[[CLLocation alloc] initWithLatitude:[mainDelegate.latitude_self doubleValue] long ...

  9. HDU 2163 Palindromes

    http://acm.hdu.edu.cn/showproblem.php?pid=2163 Problem Description Write a program to determine whet ...

  10. 【Redis】- 主从复制

    Redis跟MySQL一样,拥有非常强大的主从复制功能,而且还支持一个master可以拥有多个slave,而一个slave又可以拥有多个slave,从而形成强大的多级服务器集群架构. redis的主从 ...