Java Zip File zipFile(File source, File target)

Here you can find the source of zipFile(File source, File target)

Description

Simple method to zip up a file

License

Apache License

Parameter

Parameter Description
source The file to be zipped
target The target zip file

Declaration

public static final void zipFile(File source, File target) throws IOException 

Method Source Code


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

import java.io.*;

import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;

public class Main {
    /**/*from  w  w w .j a  v a  2  s  . c  o m*/
     * Simple method to zip up a file
     *
     * @param source The file to be zipped
     * @param target The target zip file
     */
    public static final void zipFile(File source, File target) throws IOException {

        FileOutputStream fo = new FileOutputStream(target);
        ZipOutputStream zo = new ZipOutputStream(fo);
        zo.setMethod(ZipOutputStream.DEFLATED);

        FileInputStream fi = new FileInputStream(source);
        BufferedInputStream bi = new BufferedInputStream(fi);
        ZipEntry ze = new ZipEntry(source.getName());
        zo.putNextEntry(ze);

        byte[] dt = new byte[1024];
        int bCnt;
        while ((bCnt = bi.read(dt, 0, 1024)) != -1) {
            zo.write(dt, 0, bCnt);
        }
        zo.flush();
        zo.closeEntry();
        bi.close();

        zo.close();
        source.delete();
    }

    /**
     * Reads data from BufferedReader into a String
     *
     * @param reader
     * @throws IOException
     */
    public static String read(BufferedReader reader) throws IOException {
        StringBuffer tmp = new StringBuffer();
        String tmpS;
        while ((tmpS = reader.readLine()) != null) {
            tmp.append(tmpS);
        }
        return tmp.toString();
    }
}

Related

  1. zipFile(File inputFile, File outputZip)
  2. zipFile(File inputFile, String zipFilePath)
  3. zipFile(File resFile, ZipOutputStream zipout, String rootpath)
  4. zipFile(File root, String outFileFullName, String[] suffixs, String[] nameMatche, String[] nameNotMatche)
  5. zipFile(File source, File dest)
  6. zipFile(File source, File target)
  7. zipFile(File source, String basePath, ZipOutputStream zos)
  8. zipFile(File sourceFile)
  9. zipFile(File zipfile, ZipOutputStream zos, String name)