Java Zip File zipFile(File aFileToZip)

Here you can find the source of zipFile(File aFileToZip)

Description

Gets a File and creates on the same directory with the same level a new ziped version.

License

Open Source License

Parameter

Parameter Description
aFileToZip The file to create a new zip copy from

Return

The zipped File or null in case of any error.

Declaration

public static File zipFile(File aFileToZip) 

Method Source Code


//package com.java2s;
//License from project: Open Source License 

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

public class Main {
    /**/*from www. j a v  a2s .  c o  m*/
     * Gets a File and creates on the same directory with the same level a new ziped version.
     * For example if you pass C:\test.html it will create a C:\test.html.zip
     *
     * @param aFileToZip The file to create a new zip copy from
     * @return The zipped File or null in case of any error.
     */
    public static File zipFile(File aFileToZip) {
        File target = null;
        if (aFileToZip.exists() && aFileToZip.isFile()) {
            byte[] buffer = new byte[1024];
            target = new File(aFileToZip.getName() + ".zip");
            try (FileInputStream in = new FileInputStream(aFileToZip);
                    FileOutputStream fos = new FileOutputStream(target);
                    BufferedOutputStream bos = new BufferedOutputStream(fos);
                    ZipOutputStream zos = new ZipOutputStream(bos)) {
                ZipEntry ze = new ZipEntry(aFileToZip.getName());
                zos.putNextEntry(ze);
                int len;
                while ((len = in.read(buffer)) > 0) {
                    zos.write(buffer, 0, len);
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return target;
    }
}

Related

  1. zip(String zipFileName, Map entries)
  2. zip(String zipFileName, String inputFile)
  3. zip(String zipFileName, String[] zipEntries)
  4. zip(String zipName, String[] fileNames, boolean path)
  5. zip(String zipPath, Map input)
  6. zipFile(File file)
  7. zipFile(File file, File output)
  8. zipFile(File file, File zipFile)
  9. zipFile(File file, String zipFile)