Archives a list of target files into a ZIP archive - Java File Path IO

Java examples for File Path IO:Zip File

Description

Archives a list of target files into a ZIP archive

Demo Code


//package com.java2s;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.file.Path;
import java.util.List;
import java.util.zip.ZipEntry;

import java.util.zip.ZipOutputStream;

public class Main {
    protected static final int bufferSize = 1024;

    /**/*from w w w . ja va 2  s  .  c  o  m*/
     * Archives a list of target files into a ZIP archive
     * 
     * @param archive         Path to the archive
     * @param targetFiles      List of files to put into the archive
     * @throws Exception
     */
    public static void archive(Path archive, List<Path> targetFiles)
            throws Exception {
        // creates the archive
        byte[] buffer = new byte[bufferSize];
        try (ZipOutputStream zos = new ZipOutputStream(
                new FileOutputStream(archive.toFile()))) {

            //   Loop through each file
            for (Path file : targetFiles) {
                ZipEntry ze = new ZipEntry(file.getFileName().toString());
                zos.putNextEntry(ze);
                try (FileInputStream in = new FileInputStream(file.toFile())) {
                    int len;
                    while ((len = in.read(buffer)) > 0) {
                        zos.write(buffer, 0, len);
                    }
                } catch (IOException ioe_inner) {
                    throw new Exception(
                            "Error while writing a file into the archive: "
                                    + file.getFileName());
                }
                zos.closeEntry();
            }
        } catch (IOException ioe_outter) {
            throw new Exception("Error while archiving "
                    + archive.getFileName());
        }
    }
}

Related Tutorials