Bu örnekte verilen bir klasör zip'lenmektedir. Zip dosyasının adı klasör'ün adı yapılmıştır ve dosya ziplenecek klasör ile aynı klasöre konulmuştur.
1 import java.util.zip.*;
2 import java.io.*;
3 public class DirectoryZip{
4 private ZipOutputStream zos;
5 private FileOutputStream fos;
6 private String root="";
7 public void zip(String dirPath)
8 throws Exception
9 {
10 fos=new FileOutputStream(getZipFilePath(dirPath));
11 zos=new ZipOutputStream(fos);
12 zipDir("",dirPath);
13 zos.close();
14 fos.close();
15 }
16 private void zipDir(String root,String dirPath)
17 throws Exception
18 {
19 File dir=new File(dirPath);
20 if(dir.isDirectory()){
21 File[] files=dir.listFiles();
22 for(int i=0;i<files.length;i++){
23 if(files[i].isDirectory()){
24 if(!root.equals("")){
25 zipDir(root+"\\"+dir.getName(),files[i].getPath());
26 }else{
27 zipDir(dir.getName(),files[i].getPath());
28 }
29 }else if(files[i].isFile()){
30 if(!root.equals("")){
31 zipFile(root+"\\"+dir.getName(),files[i].getPath());
32 }else{
33 zipFile(dir.getName(),files[i].getPath());
34 }
35 }
36 }
37 }
38 }
39 private void zipFile(String root,String filepath)
40 throws Exception
41 {
42 System.out.println(filepath+" zipleniyor...");
43 File file=new File(filepath);
44 FileInputStream fis=new FileInputStream(file);
45 BufferedInputStream bis=new BufferedInputStream(fis);
46 ZipEntry fileEntry=new ZipEntry(root+"\\"+file.getName());
47 zos.putNextEntry(fileEntry);
48 byte data[]=new byte[2048];
49 int count;
50 while((count=bis.read(data,0,2048))!=-1){
51 zos.write(data,0,count);
52 }
53 bis.close();
54 fis.close();
55 }
56 private String getZipFilePath(String dirPath){
57 File dir=new File(dirPath);
58 String name=dir.getName();
59 String parent=dir.getParent();
60 String zipFilePath=parent+File.separator+name+".zip";
61 return zipFilePath;
62 }
63 public static void main(String[] args) {
64 String dir=args[0];
65 DirectoryZip zipper=new DirectoryZip();
66 try{
67 zipper.zip(dir);
68 }catch(Exception e){
69 e.printStackTrace();
70 }
71 }
72 }