Example usage for java.util.zip ZipOutputStream close

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

Introduction

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

Prototype

public void close() throws IOException 

Source Link

Document

Closes the ZIP output stream as well as the stream being filtered.

Usage

From source file:de.uniwue.info6.database.jaxb.ScenarioExporter.java

/**
 *
 *
 * @param files/* w  w w  .  j  a v a 2  s. c  o m*/
 * @param zipfile
 * @return
 */
private File zip(List<File> files, File zipfile) {
    byte[] buf = new byte[1024];
    try {
        ZipOutputStream out = new ZipOutputStream(new FileOutputStream(zipfile));
        for (int i = 0; i < files.size(); i++) {
            FileInputStream in = new FileInputStream(files.get(i));
            out.putNextEntry(new ZipEntry(files.get(i).getName()));
            int len;
            while ((len = in.read(buf)) > 0) {
                out.write(buf, 0, len);
            }
            out.closeEntry();
            in.close();
        }
        out.close();
        for (File file : files) {
            if (file.isFile() && file.exists() && file.canWrite()) {
                file.delete();
            }
        }
        return zipfile;
    } catch (Exception e) {
        LOGGER.error("FAILED TO ZIP FILES", e);
    }
    return null;
}

From source file:de.xwic.appkit.core.util.ZipUtil.java

/**
 * Zips the files array into a file that has the name given as parameter.
 * /*from  w w w  .  j  a v a  2 s  . c o  m*/
 * @param files
 *            the files array
 * @param zipFileName
 *            the name for the zip file
 * @return the new zipped file
 * @throws IOException
 */
public static File zip(File[] files, String zipFileName) throws IOException {

    FileOutputStream stream = null;
    ZipOutputStream out = null;
    File archiveFile = null;

    try {

        if (!zipFileName.endsWith(".zip")) {
            zipFileName = zipFileName + ".zip";
        }

        archiveFile = new File(zipFileName);
        byte buffer[] = new byte[BUFFER_SIZE];

        // Open archive file
        stream = new FileOutputStream(archiveFile);
        out = new ZipOutputStream(stream);

        for (int i = 0; i < files.length; i++) {

            if (null == files[i] || !files[i].exists() || files[i].isDirectory()) {
                continue;
            }

            log.info("Zipping " + files[i].getName());

            // Add archive entry
            ZipEntry zipAdd = new ZipEntry(files[i].getName());
            zipAdd.setTime(files[i].lastModified());
            out.putNextEntry(zipAdd);

            // Read input & write to output
            FileInputStream in = new FileInputStream(files[i]);
            while (true) {

                int nRead = in.read(buffer, 0, buffer.length);

                if (nRead <= 0) {
                    break;
                }

                out.write(buffer, 0, nRead);
            }

            in.close();
        }

    } catch (IOException e) {

        log.error("Error: " + e.getMessage(), e);
        throw e;

    } finally {

        try {

            if (null != out) {
                out.close();
            }

            if (null != stream) {
                stream.close();
            }
        } catch (IOException e) {
            log.error("Error: " + e.getMessage(), e);
            throw e;
        }

    }

    return archiveFile;

}

From source file:com.siemens.sw360.portal.portlets.admin.ComponentUploadPortlet.java

public void backUpLicenses(ResourceRequest request, ResourceResponse response) throws IOException, TException {
    Map<String, InputStream> fileNameToStreams = getFilenameToCSVStreams();

    final ByteArrayOutputStream outB = new ByteArrayOutputStream();
    final ZipOutputStream zipOutputStream = new ZipOutputStream(outB);

    for (Map.Entry<String, InputStream> entry : fileNameToStreams.entrySet()) {
        ZipTools.addToZip(zipOutputStream, entry.getKey(), entry.getValue());
    }//  w  w w . j a  va 2s. co m

    zipOutputStream.flush();
    zipOutputStream.close(); // this closes outB

    final ByteArrayInputStream zipFile = new ByteArrayInputStream(outB.toByteArray());
    PortletResponseUtil.sendFile(request, response, "LicensesBackup.lics", zipFile, "application/zip");
}

From source file:S3DataManagerTest.java

@Test
public void testZipSourceEmptyDir() throws Exception {
    clearSourceDirectory();//from   ww  w  .  j  a v  a 2 s  .co m

    ZipOutputStream out = new ZipOutputStream(new FileOutputStream("/tmp/source.zip"));
    S3DataManager dataManager = createDefaultSource();
    dataManager.zipSource("/tmp/source/", out, "/tmp/source/");
    out.close();

    File zip = new File("/tmp/source.zip");
    assertTrue(zip.exists());

    File unzipFolder = new File("/tmp/folder/");
    unzipFolder.mkdir();
    ZipFile z = new ZipFile(zip.getPath());
    assertFalse(z.isValidZipFile()); //checks that zipfile is empty
}

From source file:S3DataManagerTest.java

@Test
public void testZipSourceBuildSpec() throws Exception {
    clearSourceDirectory();/*  w  w  w  .j ava 2  s . com*/
    String buildSpecName = "Buildspec.yml";
    File buildSpec = new File("/tmp/source/" + buildSpecName);
    String buildSpecContents = "yo\n";
    FileUtils.write(buildSpec, buildSpecContents);

    ZipOutputStream out = new ZipOutputStream(new FileOutputStream("/tmp/source.zip"));
    S3DataManager dataManager = createDefaultSource();
    dataManager.zipSource("/tmp/source/", out, "/tmp/source/");
    out.close();

    File zip = new File("/tmp/source.zip");
    assertTrue(zip.exists());

    File unzipFolder = new File("/tmp/folder/");
    unzipFolder.mkdir();
    ZipFile z = new ZipFile(zip.getPath());
    z.extractAll(unzipFolder.getPath());
    assertTrue(unzipFolder.list().length == 1);
    assertEquals(buildSpecName, unzipFolder.list()[0]);
    File extractedBuildSpec = new File(unzipFolder.getPath() + "/" + buildSpecName);
    assertTrue(FileUtils.readFileToString(extractedBuildSpec).equals(buildSpecContents));
}

From source file:S3DataManagerTest.java

@Test
public void testZipSourceOneDirEmpty() throws Exception {
    clearSourceDirectory();/*from   ww w .j  a  v a 2  s. c om*/
    String buildSpecName = "Buildspec.yml";
    File buildSpec = new File("/tmp/source/" + buildSpecName);
    String buildSpecContents = "yo\n";
    FileUtils.write(buildSpec, buildSpecContents);
    File sourceDir = new File("/tmp/source/src");
    sourceDir.mkdir();

    ZipOutputStream out = new ZipOutputStream(new FileOutputStream("/tmp/source.zip"));
    S3DataManager dataManager = createDefaultSource();
    dataManager.zipSource("/tmp/source/", out, "/tmp/source/");
    out.close();

    File zip = new File("/tmp/source.zip");
    assertTrue(zip.exists());

    File unzipFolder = new File("/tmp/folder/");
    unzipFolder.mkdir();
    ZipFile z = new ZipFile(zip.getPath());
    z.extractAll(unzipFolder.getPath());
    assertTrue(unzipFolder.list().length == 1);
    assertTrue(unzipFolder.list()[0].equals(buildSpecName));
    File extractedBuildSpec = new File(unzipFolder.getPath() + "/" + buildSpecName);
    assertTrue(FileUtils.readFileToString(extractedBuildSpec).equals(buildSpecContents));
}

From source file:com.taobao.android.builder.tools.zip.ZipUtils.java

public static void addFileAndDirectoryToZip(File output, File srcDir, Map<String, ZipEntry> zipEntryMethodMap)
        throws Exception {
    if (output.isDirectory()) {
        throw new IOException("This is a directory!");
    }/*from  w  w  w . j  a v  a2s .  co m*/
    if (!output.getParentFile().exists()) {
        output.getParentFile().mkdirs();
    }

    if (!output.exists()) {
        output.createNewFile();
    }
    List fileList = getSubFiles(srcDir);
    ZipOutputStream zos = new ZipOutputStream(new FileOutputStream(output));
    ZipEntry ze = null;
    byte[] buf = new byte[1024];
    int readLen = 0;
    for (int i = 0; i < fileList.size(); i++) {
        File f = (File) fileList.get(i);
        ze = new ZipEntry(getAbsFileName(srcDir.getPath(), f));
        ze.setSize(f.length());
        ze.setTime(f.lastModified());
        if (zipEntryMethodMap != null) {
            ZipEntry originEntry = zipEntryMethodMap.get(f.getAbsolutePath());
            if (originEntry != null) {
                ze.setCompressedSize(originEntry.getCompressedSize());
                ze.setCrc(originEntry.getCrc());
                ze.setMethod(originEntry.getMethod());
            }
        }
        zos.putNextEntry(ze);
        InputStream is = new BufferedInputStream(new FileInputStream(f));
        while ((readLen = is.read(buf, 0, 1024)) != -1) {
            zos.write(buf, 0, readLen);
        }
        is.close();
    }
    zos.close();
}

From source file:it.geosolutions.tools.compress.file.Compressor.java

/**
 * This function zip the input file.//  w  ww.  j av a 2 s.c om
 * 
 * @param file
 *            The input file to be zipped.
 * @param out
 *            The zip output stream.
 * @throws IOException
 */
public static void zipFile(final File file, final ZipOutputStream out) throws IOException {

    if (file != null && out != null) {

        // ///////////////////////////////////////////
        // Create a buffer for reading the files
        // ///////////////////////////////////////////

        byte[] buf = new byte[4096];

        FileInputStream in = null;

        try {
            in = new FileInputStream(file);

            // //////////////////////////////////
            // Add ZIP entry to output stream.
            // //////////////////////////////////

            out.putNextEntry(new ZipEntry(FilenameUtils.getName(file.getAbsolutePath())));

            // //////////////////////////////////////////////
            // Transfer bytes from the file to the ZIP file
            // //////////////////////////////////////////////

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

            // //////////////////////
            // Complete the entry
            // //////////////////////

            out.closeEntry();

        } catch (IOException e) {
            if (LOGGER.isErrorEnabled())
                LOGGER.error(e.getLocalizedMessage(), e);
            if (out != null)
                out.close();
        } finally {
            if (in != null)
                in.close();
        }

    } else
        throw new IOException("One or more input parameters are null!");
}

From source file:S3DataManagerTest.java

@Test
public void testZipSourceHugeFile() throws Exception {
    clearSourceDirectory();/*from w  w  w . ja  va 2 s.com*/
    String buildSpecName = "buildspec.yml";
    File buildSpec = new File("/tmp/source/" + buildSpecName);

    StringBuilder contents = new StringBuilder();

    for (int i = 0; i < 50000; i++) {
        contents.append("123234345456567678456234");
    }

    FileUtils.write(buildSpec, contents.toString());

    ZipOutputStream out = new ZipOutputStream(new FileOutputStream("/tmp/source.zip"));
    S3DataManager dataManager = createDefaultSource();
    dataManager.zipSource("/tmp/source/", out, "/tmp/source/");
    out.close();

    File zip = new File("/tmp/source.zip");
    assertTrue(zip.exists());

    File unzipFolder = new File("/tmp/folder/");
    unzipFolder.mkdir();
    ZipFile z = new ZipFile(zip.getPath());
    z.extractAll(unzipFolder.getPath());
    assertTrue(unzipFolder.list().length == 1);
    assertTrue(unzipFolder.list()[0].equals(buildSpecName));

    File extractedBuildSpec = new File(unzipFolder.getPath() + "/" + buildSpecName);
    assertTrue(FileUtils.readFileToString(extractedBuildSpec).equals(contents.toString()));
}

From source file:be.neutrinet.ispng.vpn.api.VPNClientConfig.java

protected Representation finalizeZip(List<String> config, ZipOutputStream zip, ByteArrayOutputStream baos)
        throws Exception {
    String file = "";
    for (String s : config) {
        file += s + '\n';
    }//from  ww w.  j  a  va2s.c om

    if (caCert == null) {
        caCert = IOUtils.toByteArray(new FileInputStream(VPN.cfg.getProperty("ca.crt")));
    }

    ZipEntry configFile = new ZipEntry("neutrinet.ovpn");
    configFile.setCreationTime(FileTime.from(Instant.now()));
    zip.putNextEntry(configFile);
    zip.write(file.getBytes());
    zip.putNextEntry(new ZipEntry("ca.crt"));
    zip.write(caCert);

    zip.close();

    ByteArrayRepresentation rep = new ByteArrayRepresentation(baos.toByteArray());
    rep.setMediaType(MediaType.APPLICATION_ZIP);
    rep.setSize(baos.size());
    rep.setCharacterSet(CharacterSet.UTF_8);
    rep.setDisposition(new Disposition(Disposition.TYPE_ATTACHMENT));
    return rep;
}