Java Zip Folder doZip(String baseDir, String fileName)

Here you can find the source of doZip(String baseDir, String fileName)

Description

do Zip

License

Open Source License

Declaration

@SuppressWarnings("rawtypes")
    public static void doZip(String baseDir, String fileName) throws Exception 

Method Source Code


//package com.java2s;
import java.io.BufferedInputStream;

import java.io.File;
import java.io.FileInputStream;

import java.io.FileOutputStream;

import java.io.InputStream;

import java.util.ArrayList;
import java.util.List;

import java.util.zip.ZipEntry;

import java.util.zip.ZipOutputStream;

public class Main {
    @SuppressWarnings("rawtypes")
    public static void doZip(String baseDir, String fileName) throws Exception {
        List fileList = getSubFiles(new File(baseDir));
        ZipOutputStream zos = new ZipOutputStream(new FileOutputStream(fileName));
        ZipEntry ze = null;//from ww w  .  j  a  va2 s  .  c  o  m
        byte[] buf = new byte[1024];
        int readLen = 0;
        for (int i = 0; i < fileList.size(); i++) {
            File f = (File) fileList.get(i);
            ze = new ZipEntry(getAbsFileName(baseDir, f));
            ze.setSize(f.length());
            ze.setTime(f.lastModified());
            zos.putNextEntry(ze);
            InputStream is = new BufferedInputStream(new FileInputStream(f));
            while ((readLen = is.read(buf, 0, 1024)) != -1) {
                zos.write(buf, 0, readLen);
            }
            is.close();
        }
        zos.close();
    }

    public static List<File> getSubFiles(File baseDir) {
        List<File> ret = new ArrayList<File>();
        File[] tmp = baseDir.listFiles();
        for (int i = 0; i < tmp.length; i++) {
            if (tmp[i].isFile())
                ret.add(tmp[i]);
            if (tmp[i].isDirectory())
                ret.addAll(getSubFiles(tmp[i]));
        }
        return ret;
    }

    private static String getAbsFileName(String baseDir, File realFileName) {
        File real = realFileName;
        File base = new File(baseDir);
        String ret = real.getName();
        while (true) {
            real = real.getParentFile();
            if (real == null)
                break;
            if (real.equals(base))
                break;
            else
                ret = real.getName() + "/" + ret;
        }
        return ret;
    }
}

Related

  1. addFolderToZip(String path, String srcFolder, ZipOutputStream zip, boolean includeFullPath)
  2. addFolderToZip(String pathInsideZip, final File folderToZip, final ZipOutputStream outZip)
  3. doZip(File fileIn, String fileOut)
  4. doZip(Map zipStructure, File zipFile)
  5. doZip(Properties properties, String name, File f)
  6. doZip(String filename, String zipFileName)
  7. doZip(String inFilePath, String outFilePath)
  8. doZipFile(ZipOutputStream zipOut, File file, String dirPath)
  9. zip(File rootDir, String zipPath)