---
title: "Java使用Zip包压缩文件示例"
author: "zywang"
date: "2011-02-22T17:24:23Z"
tags: []
categories: ["编程语言"]
slug: "java-zip"
draft: false
lastmod: "2011-02-22T17:24:23Z"
id: 916638
url: "https://zywang.iteye.com/blog/916638"
---

无描述，有代码，你懂的

```
	public static void zip() throws FileNotFoundException, IOException {
		File root = new File("svn-1.6");
		ZipOutputStream zipOutputStream = new ZipOutputStream(new FileOutputStream(root.getPath()+".zip"));
		
		zipDirectory(root,zipOutputStream);
		
		zipOutputStream.close();
	}
	
	private static void zipDirectory(File root,ZipOutputStream zipOutputStream) throws IOException{
		String zipPath = "";
		zipDirectory(zipPath,root,zipOutputStream);
	}
	
	private static void zipDirectory(String basePath,File root,ZipOutputStream zipOutputStream) throws IOException{
		if(basePath.length()>0){
			basePath += "/";
		}
		File[] files = root.listFiles();
		for (int i = 0; i < files.length; i++) {
			File file = files[i];
			if(file.isFile()){
				System.out.println(file.getPath());
				ZipEntry zipEntry = new ZipEntry(basePath + file.getName());
				zipOutputStream.putNextEntry(zipEntry);
				
				FileInputStream inputStream = new FileInputStream(file);
				int count;byte[] buffer = new byte[1024];
				while((count = inputStream.read(buffer, 0, buffer.length))>0){
					zipOutputStream.write(buffer, 0, count);
				}
				inputStream.close();
			}else if(file.isDirectory()){
				ZipEntry zipEntry = new ZipEntry(basePath + file.getName()+"/");
				zipOutputStream.putNextEntry(zipEntry);
				zipDirectory(basePath + file.getName(),file,zipOutputStream);
			}
		}
	}
```