---
title: "压缩解压性能探究"
author: "Jason__Chen"
date: "2010-12-08T09:21:21Z"
tags: []
categories: ["编程语言"]
slug: "untitled"
draft: false
lastmod: "2010-12-08T09:21:21Z"
id: 836327
url: "https://jason--chen.iteye.com/blog/836327"
---

**压缩解压性能探究**
     最近正在做一个项目，最终需要通过JAVA将一部分内容打包通过FTP上传到另外一台服务器上，当时压缩方法是这么做的：（先帖一个Test）

```java

public class Test {
	public static void main(String[] args) {
		try {
			Date date1 = new Date();
			ZipOutputStream out = new ZipOutputStream(new FileOutputStream("test.zip"));
			File inputFile = new File("d://test");
			new Test().zip(out, inputFile, "");
			out.close();
			Date date2 = new Date();
			System.out.println("耗时："+(date2.getTime()-date1.getTime()));
		} catch (Exception e) {
			e.printStackTrace();
		}

	}

	private void zip(ZipOutputStream out, File f, String base) throws Exception {
		if (f.isDirectory()) {
			File[] fl = f.listFiles();
			out.putNextEntry(new ZipEntry(base + "/"));
			base = base.length() == 0 ? "" : base + "/";
			for (int i = 0; i < fl.length; i++) {
				zip(out, fl[i], base + fl[i].getName());
			}
		} else {
			out.putNextEntry(new ZipEntry(base));
			FileInputStream in = new FileInputStream(f);
			int b;
			while ((b = in.read()) != -1) {
				out.write(b);
			}
			in.close();
		}
  	}
}

```

     使用这种压缩方式效率极其低下，为了使效率提高，我先后发现了两种方法，第一种方法是利用BufferedInputStream和BufferedOutputStream对文件流进行包装，具体代码如下：

```java

private void zip(ZipOutputStream out, File f, String base) throws Exception {
		if (f.isDirectory()) {
			File[] fl = f.listFiles();
			out.putNextEntry(new ZipEntry(base + "/"));
			base = base.length() == 0 ? "" : base + "/";
			for (int i = 0; i < fl.length; i++) {
				zip(out, fl[i], base + fl[i].getName());
			}
		} else {
			out.putNextEntry(new ZipEntry(base));
			BufferedOutputStream bou = new BufferedOutputStream(out);
			BufferedInputStream in = new BufferedInputStream(new FileInputStream(f));
			int b;
			while ((b = in.read()) != -1) {
				bou.write(b);
			}
			in.close();
			bou.flush();
		}
        }

```

     虽然第二种方式使用之后速度得到明显提升，但第三种方式较第二种还快了几倍，那就是在读写的时候增加每次读写量，具体代码如下：

```java

private void zip(ZipOutputStream out, File f, String base) throws Exception {
		if (f.isDirectory()) {
			File[] fl = f.listFiles();
			out.putNextEntry(new ZipEntry(base + "/"));
			base = base.length() == 0 ? "" : base + "/";
			for (int i = 0; i < fl.length; i++) {
				zip(out, fl[i], base + fl[i].getName());
			}
		} else {
		      out.putNextEntry(new ZipEntry(base));
		      FileInputStream in = new FileInputStream(f);
		      byte[] bs = new byte[10240];
		      int b;
		      while ((b = in.read(bs)) != -1) {
		          out.write(bs, 0, b); 
		      }
		      in.close();
		    }
		
	}

```

     目前就我测试的结果看，第三种方式是最快的，不知道各位博友有没有更快的方式，欢迎大家一起过来探讨。