Java Zip File List zip(File zipFile, File[] files)

Here you can find the source of zip(File zipFile, File[] files)

Description

zip

License

Open Source License

Declaration

public static void zip(File zipFile, File[] files) 

Method Source Code


//package com.java2s;
/*/*from w ww.j  a  v a 2 s .  c  om*/
 * Copyright 2016 janobono. All rights reserved.
 * Use of this source code is governed by a Apache 2.0
 * license that can be found in the LICENSE file.
 */

import java.io.*;

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

public class Main {
    public static void zip(File zipFile, File[] files) {
        byte[] buffer = new byte[1024];
        try (ZipOutputStream zos = new ZipOutputStream(new FileOutputStream(zipFile))) {
            for (File file : files) {
                ZipEntry ze = new ZipEntry(file.getName());
                zos.putNextEntry(ze);
                try (FileInputStream in = new FileInputStream(file)) {
                    int len;
                    while ((len = in.read(buffer)) > 0) {
                        zos.write(buffer, 0, len);
                    }
                }
            }
            zos.closeEntry();
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    public static byte[] read(File file) {
        try (InputStream is = new BufferedInputStream(new FileInputStream(file));
                ByteArrayOutputStream os = new ByteArrayOutputStream()) {
            byte[] buffer = new byte[1024];
            int bytesRead = 0;
            while (bytesRead != -1) {
                bytesRead = is.read(buffer);
                if (bytesRead > 0) {
                    os.write(buffer, 0, bytesRead);
                }
            }
            return os.toByteArray();
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    public static void write(File file, byte[] data) {
        try (OutputStream os = new BufferedOutputStream(new FileOutputStream(file, false))) {
            os.write(data, 0, data.length);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }
}

Related

  1. zip(Collection files, File zipFile)
  2. zip(File zipFile, File parentDir, File[] sources, char pathSeparator)
  3. zip(File zipFile, File[] files)
  4. zip(File zipFile, List files)
  5. zip(Iterable files, String baseFolderName, String toZipFile)
  6. zip(List runtimeLibFiles, File saturnContainerDir, File zipFile)