Example usage for java.util.zip ZipOutputStream closeEntry

List of usage examples for java.util.zip ZipOutputStream closeEntry

Introduction

In this page you can find the example usage for java.util.zip ZipOutputStream closeEntry.

Prototype

public void closeEntry() throws IOException 

Source Link

Document

Closes the current ZIP entry and positions the stream for writing the next entry.

Usage

From source file:org.apache.gobblin.service.modules.orchestration.AzkabanClientTest.java

private static void addDirToZipArchive(ZipOutputStream zos, File fileToZip, String parentDirectoryName)
        throws IOException {
    if (fileToZip == null || !fileToZip.exists()) {
        return;/* ww w.ja v a  2  s  .c o  m*/
    }

    String zipEntryName = fileToZip.getName();
    if (parentDirectoryName != null && !parentDirectoryName.isEmpty()) {
        zipEntryName = parentDirectoryName + "/" + fileToZip.getName();
    }

    if (fileToZip.isDirectory()) {
        for (File file : fileToZip.listFiles()) {
            addDirToZipArchive(zos, file, zipEntryName);
        }
    } else {
        byte[] buffer = new byte[1024];
        FileInputStream fis = new FileInputStream(fileToZip);
        zos.putNextEntry(new ZipEntry(zipEntryName));
        int length;
        while ((length = fis.read(buffer)) > 0) {
            zos.write(buffer, 0, length);
        }
        zos.closeEntry();
        fis.close();
    }
}

From source file:game.com.HandleDownloadFolderServlet.java

public static void addDirToZipArchive(ZipOutputStream zos, File fileToZip, String parrentDirectoryName)
        throws Exception {
    if (fileToZip == null || !fileToZip.exists()) {
        return;//from w  w  w .ja v  a  2  s  .c  o m
    }

    String zipEntryName = fileToZip.getName();
    if (parrentDirectoryName != null && !parrentDirectoryName.isEmpty()) {
        zipEntryName = parrentDirectoryName + "/" + fileToZip.getName();
    }

    if (fileToZip.isDirectory()) {
        System.out.println("+" + zipEntryName);
        for (File file : fileToZip.listFiles()) {
            addDirToZipArchive(zos, file, zipEntryName);
        }
    } else {
        System.out.println("   " + zipEntryName);
        byte[] buffer = new byte[1024];
        FileInputStream fis = new FileInputStream(fileToZip);
        zos.putNextEntry(new ZipEntry(zipEntryName));
        int length;
        while ((length = fis.read(buffer)) > 0) {
            zos.write(buffer, 0, length);
        }
        zos.closeEntry();
        fis.close();
    }
}

From source file:org.apache.beam.sdk.io.TextIOReadTest.java

License:asdf

/**
 * Create a zip file with the given lines.
 *
 * @param expected A list of expected lines, populated in the zip file.
 * @param folder A temporary folder used to create files.
 * @param filename Optionally zip file name (can be null).
 * @param fieldsEntries Fields to write in zip entries.
 * @return The zip filename.//  w ww . ja v a2 s.  c o m
 * @throws Exception In case of a failure during zip file creation.
 */
private static File createZipFile(List<String> expected, TemporaryFolder folder, String filename,
        String[]... fieldsEntries) throws Exception {
    File tmpFile = folder.getRoot().toPath().resolve(filename).toFile();

    ZipOutputStream out = new ZipOutputStream(new FileOutputStream(tmpFile));
    PrintStream writer = new PrintStream(out, true /* auto-flush on write */);

    int index = 0;
    for (String[] entry : fieldsEntries) {
        out.putNextEntry(new ZipEntry(Integer.toString(index)));
        for (String field : entry) {
            writer.println(field);
            expected.add(field);
        }
        out.closeEntry();
        index++;
    }

    writer.close();
    out.close();

    return tmpFile;
}

From source file:com.plotsquared.iserver.util.FileUtils.java

/**
 * Add files to a zip file//from   w  w w  .j a v a  2 s  . c om
 *
 * @param zipFile Zip File
 * @param files   Files to add to the zip
 * @param delete  If the original files should be deleted
 * @throws Exception If anything goes wrong
 */
public static void addToZip(final File zipFile, final File[] files, final boolean delete) throws Exception {
    Assert.notNull(zipFile, files);

    if (!zipFile.exists()) {
        if (!zipFile.createNewFile()) {
            throw new RuntimeException("Couldn't create " + zipFile);
        }
    }

    final File temporary = File.createTempFile(zipFile.getName(), "");
    //noinspection ResultOfMethodCallIgnored
    temporary.delete();

    if (!zipFile.renameTo(temporary)) {
        throw new RuntimeException("Couldn't rename " + zipFile + " to " + temporary);
    }

    final byte[] buffer = new byte[1024 * 16]; // 16mb

    ZipInputStream zis = new ZipInputStream(new FileInputStream(temporary));
    ZipOutputStream zos = new ZipOutputStream(new FileOutputStream(zipFile));

    ZipEntry e = zis.getNextEntry();
    while (e != null) {
        String n = e.getName();

        boolean no = true;
        for (File f : files) {
            if (f.getName().equals(n)) {
                no = false;
                break;
            }
        }

        if (no) {
            zos.putNextEntry(new ZipEntry(n));
            int len;
            while ((len = zis.read(buffer)) > 0) {
                zos.write(buffer, 0, len);
            }
        }
        e = zis.getNextEntry();
    }
    zis.close();
    for (File file : files) {
        InputStream in = new FileInputStream(file);
        zos.putNextEntry(new ZipEntry(file.getName()));

        int len;
        while ((len = in.read(buffer)) > 0) {
            zos.write(buffer, 0, len);
        }

        zos.closeEntry();
        in.close();
    }
    zos.close();
    temporary.delete();

    if (delete) {
        for (File f : files) {
            f.delete();
        }
    }
}

From source file:edu.umd.cs.submit.CommandLineSubmit.java

/**
 * @param p/*from ww  w . ja  v a2 s . c om*/
 * @param find
 * @param files
 * @param userProps
 * @return
 * @throws IOException
 * @throws FileNotFoundException
 */
public static MultipartPostMethod createFilePost(Properties p, FindAllFiles find, Collection<File> files,
        Properties userProps) throws IOException, FileNotFoundException {
    // ========================== assemble zip file in byte array
    // ==============================
    String loginName = userProps.getProperty("loginName");
    String classAccount = userProps.getProperty("classAccount");
    String from = classAccount;
    if (loginName != null && !loginName.equals(classAccount))
        from += "/" + loginName;
    System.out.println(" submitted by " + from);
    System.out.println();
    System.out.println("Submitting the following files");
    ByteArrayOutputStream bytes = new ByteArrayOutputStream(4096);
    byte[] buf = new byte[4096];
    ZipOutputStream zipfile = new ZipOutputStream(bytes);
    zipfile.setComment("zipfile for CommandLineTurnin, version " + VERSION);
    for (File resource : files) {
        if (resource.isDirectory())
            continue;
        String relativePath = resource.getCanonicalPath().substring(find.rootPathLength + 1);
        System.out.println(relativePath);
        ZipEntry entry = new ZipEntry(relativePath);
        entry.setTime(resource.lastModified());

        zipfile.putNextEntry(entry);
        InputStream in = new FileInputStream(resource);
        try {
            while (true) {
                int n = in.read(buf);
                if (n < 0)
                    break;
                zipfile.write(buf, 0, n);
            }
        } finally {
            in.close();
        }
        zipfile.closeEntry();

    } // for each file
    zipfile.close();

    MultipartPostMethod filePost = new MultipartPostMethod(p.getProperty("submitURL"));

    p.putAll(userProps);
    // add properties
    for (Map.Entry<?, ?> e : p.entrySet()) {
        String key = (String) e.getKey();
        String value = (String) e.getValue();
        if (!key.equals("submitURL"))
            filePost.addParameter(key, value);
    }
    filePost.addParameter("submitClientTool", "CommandLineTool");
    filePost.addParameter("submitClientVersion", VERSION);
    byte[] allInput = bytes.toByteArray();
    filePost.addPart(new FilePart("submittedFiles", new ByteArrayPartSource("submit.zip", allInput)));
    return filePost;
}

From source file:org.cloudfoundry.client.lib.io.DynamicZipInputStreamTest.java

@Test
public void shouldCreateValidZipContent() throws Exception {

    byte[] f1 = newRandomBytes(10000);
    byte[] f2 = newRandomBytes(10000);

    ByteArrayOutputStream bos = new ByteArrayOutputStream();
    ZipOutputStream zipOutputStream = new ZipOutputStream(bos);
    zipOutputStream.putNextEntry(new ZipEntry("a/b/c"));
    zipOutputStream.write(f1);/*from  ww w .java 2  s.  c om*/
    zipOutputStream.closeEntry();
    zipOutputStream.putNextEntry(new ZipEntry("a/b/c/d/"));
    zipOutputStream.closeEntry();
    zipOutputStream.putNextEntry(new ZipEntry("d/e/f"));
    zipOutputStream.write(f2);
    zipOutputStream.closeEntry();
    zipOutputStream.flush();
    zipOutputStream.close();
    byte[] expected = bos.toByteArray();

    List<DynamicZipInputStream.Entry> entries = new ArrayList<DynamicZipInputStream.Entry>();
    entries.add(newEntry("a/b/c", f1));
    entries.add(newEntry("a/b/c/d/", null));
    entries.add(newEntry("d/e/f", f2));
    DynamicZipInputStream inputStream = new DynamicZipInputStream(entries);
    bos.reset();
    FileCopyUtils.copy(inputStream, bos);
    byte[] actual = bos.toByteArray();

    assertThat(actual, is(equalTo(expected)));
}

From source file:nz.co.fortytwo.signalk.util.ZipUtils.java

/**
 * Add the directory recursively into a zip file
 * @param zout//from   w ww.j  a  v a2s  .com
 * @param fileSource
 * @param sourceDir
 */
private static void addDirectory(ZipOutputStream zout, File fileSource, File sourceDir) {

    // get sub-folder/files list
    File[] files = fileSource.listFiles();

    logger.debug("Adding directory " + fileSource.getName());

    for (int i = 0; i < files.length; i++) {
        try {
            String name = files[i].getAbsolutePath();
            name = name.substring((int) sourceDir.getAbsolutePath().length());
            // if the file is directory, call the function recursively
            if (files[i].isDirectory()) {
                addDirectory(zout, files[i], sourceDir);
                continue;
            }

            /*
             * we are here means, its file and not directory, so
             * add it to the zip file
             */

            logger.debug("Adding file " + files[i].getName());

            // create object of FileInputStream
            FileInputStream fin = new FileInputStream(files[i]);

            zout.putNextEntry(new ZipEntry(name));

            IOUtils.copy(fin, zout);

            zout.closeEntry();

            // close the InputStream
            fin.close();

        } catch (IOException ioe) {
            logger.error(ioe.getMessage(), ioe);
        }
    }

}

From source file:nz.co.fortytwo.freeboard.installer.ZipUtils.java

/**
 * Add the directory recursively into a zip file
 * @param zout//from w  ww .j  av  a  2  s. c  o  m
 * @param fileSource
 * @param sourceDir
 */
private static void addDirectory(ZipOutputStream zout, File fileSource, File sourceDir) {

    // get sub-folder/files list
    File[] files = fileSource.listFiles();

    logger.debug("Adding directory " + fileSource.getName());

    for (int i = 0; i < files.length; i++) {
        try {
            String name = files[i].getAbsolutePath();

            name = name.substring((int) sourceDir.getAbsolutePath().length() + 1);
            // if the file is directory, call the function recursively
            if (files[i].isDirectory()) {
                addDirectory(zout, files[i], sourceDir);
                continue;
            }

            /*
             * we are here means, its file and not directory, so
             * add it to the zip file
             */

            logger.debug("Adding file " + files[i].getName());

            // create object of FileInputStream
            FileInputStream fin = new FileInputStream(files[i]);

            zout.putNextEntry(new ZipEntry(name));

            IOUtils.copy(fin, zout);

            zout.closeEntry();

            // close the InputStream
            fin.close();

        } catch (IOException ioe) {
            logger.error(ioe.getMessage(), ioe);
        }
    }

}

From source file:net.sourceforge.fenixedu.presentationTier.Action.externalServices.epfl.ExportPhdIndividualProgramProcessesInHtml.java

static byte[] createZip(final PhdProgramPublicCandidacyHashCode hashCode) {

    final ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
    ZipOutputStream zip = null;
    try {//w w w . j a  v a  2s. c o  m
        zip = new ZipOutputStream(outputStream);

        int count = 1;
        for (final PhdProgramProcessDocument document : hashCode.getIndividualProgramProcess()
                .getCandidacyProcessDocuments()) {
            final ZipEntry zipEntry = new ZipEntry(count + "-" + document.getFilename());
            zip.putNextEntry(zipEntry);

            // TODO: use in local context copy(new ByteArrayInputStream(new
            // byte[20]), zip);
            copy(document.getStream(), zip);

            zip.closeEntry();
            count++;
        }
    } catch (FileNotFoundException e) {
        logger.error(e.getMessage(), e);
    } catch (IOException e) {
        logger.error(e.getMessage(), e);
    } finally {
        if (zip != null) {
            try {
                zip.flush();
                zip.close();
            } catch (IOException e) {
                logger.error(e.getMessage(), e);
            }
        }
    }
    return outputStream.toByteArray();
}

From source file:org.apache.brooklyn.rest.resources.BundleAndTypeResourcesTest.java

private static File createZip(Map<String, String> files) throws Exception {
    File f = Os.newTempFile("osgi", "zip");

    ZipOutputStream zip = new ZipOutputStream(new FileOutputStream(f));

    for (Map.Entry<String, String> entry : files.entrySet()) {
        ZipEntry ze = new ZipEntry(entry.getKey());
        zip.putNextEntry(ze);/*from   w  ww . ja va  2s . c  o  m*/
        zip.write(entry.getValue().getBytes());
    }

    zip.closeEntry();
    zip.flush();
    zip.close();

    return f;
}