需要 ant.jar包

 

 

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;

import org.apache.tools.zip.ZipEntry;
import org.apache.tools.zip.ZipOutputStream;


public class ZipDemo3 
{
	public static void main(String [] args)
	{
		File dir = new File("F:"+File.separator+"皓皓的生日礼物");
		File zip = new File("F:"+File.separator+"皓皓的生日礼物.zip");
		ZipOutputStream zo = null;
		try {
			zo = new ZipOutputStream(new FileOutputStream(zip));
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		}
		
		zipFile(dir,zo,"");
		
		if(zo!=null)
		{
				try {
					zo.close();
				} catch (IOException e) {
					e.printStackTrace();
				}	
		}
	}

	private static void zipFile(File dir, ZipOutputStream zo,String base)
	{
		
	
		try {
			
			zo.setEncoding("GBK");//防止中文乱码现象的出现
			zo.setComment("压缩文件夹Demo");
		
			boolean firstDir = false;
			if(dir.isDirectory())
			{
				   firstDir = true;
				   File [] subFiles = dir.listFiles();
				  
				   zo.putNextEntry(new ZipEntry(base+"/"));
				   base = base.length() == 0 ? "" : base + "/";
				   for (File file :subFiles) 
				   {
					 zipFile(file,zo,base+file.getName());		
				   }
			}else
			{
				InputStream is = new FileInputStream(dir);
				 System.out.println(base);
				 if( !firstDir )
				 {
					 zo.putNextEntry(new ZipEntry(dir.getName()));
				 }else
				zo.putNextEntry(new ZipEntry(base));
				
				int len = 0;
				byte [] buf = new byte[BUF];
				while((len = is.read(buf))!=-1)
				{
					zo.write(buf, 0, len);
				}
				zo.flush();

				if(is!=null)
				{
						is.close();	
				}
				
			}

			
			
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		

		
	}
public static int BUF = 1024*10;

}