Java Zip File zipFile(File inputFile, String zipFilePath)

Here you can find the source of zipFile(File inputFile, String zipFilePath)

Description

zip File

License

Apache License

Declaration

public static void zipFile(File inputFile, String zipFilePath) 

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 {
    public static void zipFile(File inputFile, String zipFilePath) {
        try {//from   ww  w .j a  v  a  2  s.c  om

            // Wrap a FileOutputStream around a ZipOutputStream
            // to store the zip stream to a file. Note that this is
            // not absolutely necessary
            FileOutputStream fileOutputStream = new FileOutputStream(zipFilePath);
            ZipOutputStream zipOutputStream = new ZipOutputStream(fileOutputStream);

            // a ZipEntry represents a file entry in the zip archive
            // We name the ZipEntry after the original file's name
            ZipEntry zipEntry = new ZipEntry(inputFile.getName());
            zipOutputStream.putNextEntry(zipEntry);

            FileInputStream fileInputStream = new FileInputStream(inputFile);
            byte[] buf = new byte[1024];
            int bytesRead;

            // Read the input file by chucks of 1024 bytes
            // and write the read bytes to the zip stream
            while ((bytesRead = fileInputStream.read(buf)) > 0) {
                zipOutputStream.write(buf, 0, bytesRead);
            }

            // close ZipEntry to store the stream to the file
            zipOutputStream.closeEntry();

            zipOutputStream.close();
            fileOutputStream.close();

            System.out.println(
                    "Regular file :" + inputFile.getCanonicalPath() + " is zipped to archive :" + zipFilePath);

        } catch (IOException e) {
            e.printStackTrace();
        }

    }
}

Related

  1. zipFile(File file, File zipFile)
  2. zipFile(File file, String zipFile)
  3. zipFile(File fileToZip, String fileName, ZipOutputStream zipOut)
  4. zipFile(File input, File output)
  5. zipFile(File inputFile, File outputZip)
  6. zipFile(File resFile, ZipOutputStream zipout, String rootpath)
  7. zipFile(File root, String outFileFullName, String[] suffixs, String[] nameMatche, String[] nameNotMatche)
  8. zipFile(File source, File dest)
  9. zipFile(File source, File target)