Java Zip File Zip(String path, File file)

Here you can find the source of Zip(String path, File file)

Description

Zip

License

Apache License

Declaration

public static String Zip(String path, File file) throws IOException 

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.io.IOException;

import java.util.zip.ZipEntry;

import java.util.zip.ZipOutputStream;

public class Main {
    public static String Zip(String path, File file) throws IOException {
        if (file == null) {
            return null;
        }/*from  ww w  . j a va  2s.  com*/
        String zipFileName = "";
        if (file.getName().indexOf(".") > -1) {
            zipFileName = file.getName().substring(0, file.getName().indexOf(".")) + ".zip";
        } else {
            zipFileName = file.getName() + ".zip";
        }
        String zipFullName = path + File.separator + zipFileName;
        byte[] data = new byte[1024 * 2];
        FileInputStream fis = new FileInputStream(file);
        FileOutputStream fos = new FileOutputStream(zipFullName);
        ZipOutputStream zipOS = new ZipOutputStream(fos);
        zipOS.setMethod(ZipOutputStream.DEFLATED);
        zipOS.putNextEntry(new ZipEntry(file.getName()));
        int length = 0;
        while ((length = fis.read(data)) != -1) {
            zipOS.write(data, 0, length);
        }
        zipOS.finish();
        zipOS.close();
        fos.close();
        fis.close();
        return zipFileName;
    }

    public static String Zip(String path, String zipName, File[] files) throws IOException {
        if (files == null) {
            return null;
        }
        String zipFullName = path + File.separator + zipName;
        byte[] data = new byte[1024];
        FileOutputStream fos = new FileOutputStream(zipFullName);
        for (File file : files) {
            FileInputStream fis = new FileInputStream(file);
            ZipOutputStream zipOS = new ZipOutputStream(fos);
            zipOS.setMethod(ZipOutputStream.DEFLATED);
            zipOS.putNextEntry(new ZipEntry(file.getName()));
            int length = 0;
            while ((length = fis.read(data)) != -1) {
                zipOS.write(data, 0, length);
            }
            zipOS.finish();
            zipOS.close();
            fis.close();
        }
        fos.close();
        return zipFullName;
    }
}

Related

  1. zip(String data, String fileName)
  2. zip(String dir, String destFile)
  3. zip(String filesDirToBeZipped, String destFileName, String manifest)
  4. zip(String inputStr)
  5. zip(String outputFileName, String inputFileName)
  6. zip(String path, String zipFilePath)
  7. zip(String payload)
  8. zip(String src, String des)
  9. zip(String src, String dest, PrintStream stream)