Java Path File List nio archive(Path archive, List targetFiles)

Here you can find the source of archive(Path archive, List targetFiles)

Description

Archives a list of target files into a ZIP archive

License

Open Source License

Parameter

Parameter Description
archive Path to the archive
targetFiles List of files to put into the archive

Exception

Parameter Description
Exception an exception

Declaration

public static void archive(Path archive, List<Path> targetFiles) throws Exception 

Method Source Code


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

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  ww  w.  j av  a  2 s  . c om*/
     * 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

  1. addNonEmptyLinesFromFile(final ArrayList result, final String path)
  2. anyPathMatcher(final ImmutableList pathMatchers)
  3. asFileList(Object... paths)
  4. asPathsList(final File[] files)
  5. compileTreeWithErrors(JavaCompiler compiler, List options, File targetFolder, DiagnosticListener diagnosticListener, boolean addProcessorsToClasspath)
  6. deepListChildren(Path directory)