Java Zip File zip(String src, String des)

Here you can find the source of zip(String src, String des)

Description

zip

License

Apache License

Declaration

public static boolean zip(String src, String des) throws Exception 

Method Source Code


//package com.java2s;
//License from project: Apache License 

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;

public class Main {
    public static boolean zip(String src, String des) throws Exception {
        boolean result;
        ZipOutputStream out = null;
        try {// w w w .  jav  a2 s  .  c  o m
            File f = new File(src);
            out = new ZipOutputStream(new FileOutputStream(des));
            zip(out, f, "");
            f.delete();
            result = true;
        } catch (Exception ex) {
            result = false;
        } finally {
            out.close();
        }
        return result;
    }

    static void zip(ZipOutputStream out, File f, String base) throws Exception {
        if (f.isDirectory()) {
            File[] fl = f.listFiles();
            out.putNextEntry(new ZipEntry(base + File.separator));
            base = base.length() == 0 ? "" : base + File.separator;
            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;
            System.out.println(base);
            while ((b = in.read()) != -1) {
                out.write(b);
            }
            in.close();
        }
    }
}

Related

  1. zip(String inputStr)
  2. zip(String outputFileName, String inputFileName)
  3. Zip(String path, File file)
  4. zip(String path, String zipFilePath)
  5. zip(String payload)
  6. zip(String src, String dest, PrintStream stream)
  7. zip(String srcPath)
  8. zip(String zipFileName, Map entries)
  9. zip(String zipFileName, String inputFile)