Java的压缩与解压缩ZIP

发布时间:2016-12-08 00:00:00 编辑:嘉辉 手机版

  压缩是一种通过特定的算法来减小计算机文件大小的机制。这种机制是一种很方便的发明,尤其是对网络用户,因为它可以减小文件的字节总数,使文件能够通过较慢的互联网连接实现更快传输,此外还可以减少文件的磁盘占用空间。下面小编准备了关于Java的压缩与解压缩ZIP,提供给大家参考!

  压缩的

  import java.io.BufferedInputStream;

  import java.io.BufferedOutputStream;

  import java.io.File;

  import java.io.FileInputStream;

  import java.io.FileOutputStream;

  import java.util.zip.ZipEntry;

  import java.util.zip.ZipOutputStream;

  public class Zip {

  static final int BUFFER = 2048;

  public static void main(String argv[]) {

  try {

  BufferedInputStream origin = null;

  FileOutputStream dest = new FileOutputStream("E:\\test\\myfiles.zip");

  ZipOutputStream out = new ZipOutputStream(new BufferedOutputStream(

  dest));

  byte data[] = new byte[BUFFER];

  File f = new File("e:\\test\\a\\");

  File files[] = f.listFiles();

  for (int i = 0; i < files.length; i++) {

  FileInputStream fi = new FileInputStream(files[i]);

  origin = new BufferedInputStream(fi, BUFFER);

  ZipEntry entry = new ZipEntry(files[i].getName());

  out.putNextEntry(entry);

  int count;

  while ((count = origin.read(data, 0, BUFFER)) != -1) {

  out.write(data, 0, count);

  }

  origin.close();

  }

  out.close();

  } catch (Exception e) {

  e.printStackTrace();

  }

  }

  }

  解压缩的

  import java.io.BufferedInputStream;

  import java.io.BufferedOutputStream;

  import java.io.File;

  import java.io.FileOutputStream;

  import java.util.Enumeration;

  import java.util.zip.ZipEntry;

  import java.util.zip.ZipFile;

  public class UnZip {

  static final int BUFFER = 2048;

  public static void main(String argv[]) {

  try {

  String fileName = "E:\\test\\myfiles.zip";

  String filePath = "E:\\test\\";

  ZipFile zipFile = new ZipFile(fileName);

  Enumeration emu = zipFile.entries();

  int i=0;

  while(emu.hasMoreElements()){

  ZipEntry entry = (ZipEntry)emu.nextElement();

  //会把目录作为一个file读出一次,所以只建立目录就可以,之下的文件还会被迭代到。

  if (entry.isDirectory())

  {

  new File(filePath + entry.getName()).mkdirs();

  continue;

  }

  BufferedInputStream bis = new BufferedInputStream(zipFile.getInputStream(entry));

  File file = new File(filePath + entry.getName());

  //加入这个的原因是zipfile读取文件是随机读取的,这就造成可能先读取一个文件

  //而这个文件所在的目录还没有出现过,所以要建出目录来。

  File parent = file.getParentFile();

  if(parent != null && (!parent.exists())){

  parent.mkdirs();

  }

  FileOutputStream fos = new FileOutputStream(file);

  BufferedOutputStream bos = new BufferedOutputStream(fos,BUFFER);

  int count;

  byte data[] = new byte[BUFFER];

  while ((count = bis.read(data, 0, BUFFER)) != -1)

  {

  bos.write(data, 0, count);

  }

  bos.flush();

  bos.close();

  bis.close();

  }

  zipFile.close();

  } catch (Exception e) {

  e.printStackTrace();

  }

  }

  }

本文已影响865
+1
0