package com.java.charpter15;


import java.io.File;

import java.io.FileInputStream;

import java.io.FileNotFoundException;

import java.io.FileOutputStream;

import java.io.IOException;

import java.util.zip.ZipEntry;

import java.util.zip.ZipOutputStream;


public class MyZip {

private void zip(String zipFileName,File inputFile) throws IOException

{

ZipOutputStream out=new ZipOutputStream(new FileOutputStream(inputFile));

zip(out, inputFile,"");

System.out.println("压缩中...");

out.close();

}

private void zip(ZipOutputStream out,File f,String base) throws IOException

{

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, f, base+fl[i]);

}

}

else {

out.putNextEntry(new ZipEntry(base));

//创建FileInputStream对象

FileInputStream in=new FileInputStream(f);

int b;

System.out.println(base);

while ((b=in.read())!=-1) {

out.write(b);



}

in.close();

}



}

public static void main(String[] args) {

MyZip book=new MyZip();

try {

book.zip("E:/hello.zip", new File("D:\\Data"));

System.out.println("压缩完成");

} catch (Exception e) {

e.printStackTrace();

}











}






}