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:cdr.forms.SwordDepositHandler.java

private File makeZipFile(gov.loc.mets.DocumentRoot metsDocumentRoot,
        IdentityHashMap<DepositFile, String> filenames) {

    // Get the METS XML

    String metsXml = serializeMets(metsDocumentRoot);

    // Create the zip file

    File zipFile;//  w w w  .  j  a  va 2s  .  c  om

    try {
        zipFile = File.createTempFile("tmp", ".zip");
    } catch (IOException e) {
        throw new Error(e);
    }

    FileOutputStream fileOutput;

    try {
        fileOutput = new FileOutputStream(zipFile);
    } catch (FileNotFoundException e) {
        throw new Error(e);
    }

    ZipOutputStream zipOutput = new ZipOutputStream(fileOutput);

    try {

        ZipEntry entry;

        // Write the METS

        entry = new ZipEntry("mets.xml");
        zipOutput.putNextEntry(entry);

        PrintStream xmlPrintStream = new PrintStream(zipOutput);
        xmlPrintStream.print(metsXml);

        // Write files

        for (DepositFile file : filenames.keySet()) {

            if (!file.isExternal()) {

                entry = new ZipEntry(filenames.get(file));
                zipOutput.putNextEntry(entry);

                FileInputStream fileInput = new FileInputStream(file.getFile());

                byte[] buffer = new byte[1024];
                int length;

                while ((length = fileInput.read(buffer)) != -1)
                    zipOutput.write(buffer, 0, length);

                fileInput.close();

            }

        }

        zipOutput.finish();
        zipOutput.close();

        fileOutput.close();

    } catch (IOException e) {

        throw new Error(e);

    }

    return zipFile;

}

From source file:au.org.ala.bhl.service.DocumentCacheService.java

public void compressPages(ItemDescriptor itemDesc) {
    File itemDir = new File(getItemDirectoryPath(itemDesc.getInternetArchiveId()));
    File file = getPageArchiveFile(itemDesc);
    if (file.exists()) {
        log("Deleting existing archive file: %s", file.getAbsolutePath());
        file.delete();//from  w ww. j a  v a  2s .co  m
    }
    try {
        File[] candidates = itemDir.listFiles();
        int pageCount = 0;

        ZipOutputStream out = null;

        for (File candidate : candidates) {
            Matcher m = PAGE_FILE_REGEX.matcher(candidate.getName());
            if (m.matches()) {
                if (out == null) {
                    out = new ZipOutputStream(new FileOutputStream(file));
                }
                pageCount++;
                FileInputStream in = new FileInputStream(candidate);
                out.putNextEntry(new ZipEntry(candidate.getName()));
                byte[] buf = new byte[2048];
                int len;
                while ((len = in.read(buf)) > 0) {
                    out.write(buf, 0, len);
                }
                out.closeEntry();
                in.close();

                candidate.delete();
            }
        }

        if (out != null) {
            out.close();
            log("%d pages add to pages.zip for item %s", pageCount, itemDesc);
        } else {
            log("No pages for item %s", itemDesc);
        }

    } catch (Exception ex) {
        throw new RuntimeException(ex);
    }
}

From source file:it.eng.spagobi.tools.scheduler.dispatcher.MailDocumentDispatchChannel.java

private byte[] zipDocument(String fileZipName, byte[] content) {
    logger.debug("IN");

    ByteArrayOutputStream bos = null;
    ZipOutputStream zos = null;
    ByteArrayInputStream in = null;
    try {/*from ww w .j a  v  a2  s.  c  o  m*/

        bos = new ByteArrayOutputStream();
        zos = new ZipOutputStream(bos);
        ZipEntry ze = new ZipEntry(fileZipName);
        zos.putNextEntry(ze);
        in = new ByteArrayInputStream(content);

        for (int c = in.read(); c != -1; c = in.read()) {
            zos.write(c);
        }

        return bos.toByteArray();

    } catch (IOException ex) {
        logger.error("Error zipping the document", ex);
        return null;
    } finally {
        if (bos != null) {
            try {
                bos.close();
            } catch (IOException e) {
                logger.error("Error closing output stream", e);
            }
        }
        if (zos != null) {
            try {
                zos.close();
            } catch (IOException e) {
                logger.error("Error closing output stream", e);
            }
        }
        if (in != null) {
            try {
                in.close();
            } catch (IOException e) {
                logger.error("Error closing output stream", e);
            }
        }
    }

}

From source file:com.comcast.video.dawg.show.video.VideoSnap.java

/**
 * Retrieve the images with input device ids from cache and stores it in zip
 * output stream./*from  www . j a  v a  2s . c o m*/
 *
 * @param capturedImageIds
 *            Ids of captures images
 * @param deviceMacs
 *            Mac address of selected devices
 * @param response
 *            http servelet response
 * @param session
 *            http session.
 */
public void addImagesToZipFile(String[] capturedImageIds, String[] deviceMacs, HttpServletResponse response,
        HttpSession session) {

    UniqueIndexedCache<BufferedImage> imgCache = getClientCache(session).getImgCache();

    response.setHeader("Content-Disposition",
            "attachment; filename=\"" + "Images_" + getCurrentDateAndTime() + ".zip\"");
    response.setContentType("application/zip");

    ServletOutputStream serveletOutputStream = null;
    ZipOutputStream zipOutputStream = null;

    try {
        serveletOutputStream = response.getOutputStream();
        ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
        zipOutputStream = new ZipOutputStream(byteArrayOutputStream);

        BufferedImage image;
        ZipEntry zipEntry;
        ByteArrayOutputStream imgByteArrayOutputStream = null;

        for (int i = 0; i < deviceMacs.length; i++) {
            // Check whether id of captured image is null or not
            if (!StringUtils.isEmpty(capturedImageIds[i])) {
                image = imgCache.getItem(capturedImageIds[i]);
                zipEntry = new ZipEntry(deviceMacs[i].toUpperCase() + "." + IMG_FORMAT);
                zipOutputStream.putNextEntry(zipEntry);
                imgByteArrayOutputStream = new ByteArrayOutputStream();
                ImageIO.write(image, IMG_FORMAT, imgByteArrayOutputStream);
                imgByteArrayOutputStream.flush();
                zipOutputStream.write(imgByteArrayOutputStream.toByteArray());
                zipOutputStream.closeEntry();
            }
        }

        zipOutputStream.flush();
        zipOutputStream.close();
        serveletOutputStream.write(byteArrayOutputStream.toByteArray());
    } catch (IOException ioe) {
        LOGGER.error("Image zipping failed !!!", ioe);
    } finally {
        IOUtils.closeQuietly(zipOutputStream);
    }
}

From source file:gdt.data.entity.ArchiveHandler.java

/**
 * Compress the database into the zip archive file. 
 * @param  entigrator entigrator instance
 * @param locator$ container of arguments in the string form. 
 * @return true if success false otherwise.
 *//*from w w  w  .  j  av a2s.co  m*/
public boolean compressDatabaseToZip(Entigrator entigrator, String locator$) {
    try {
        Properties locator = Locator.toProperties(locator$);
        archiveType$ = locator.getProperty(ARCHIVE_TYPE);
        archiveFile$ = locator.getProperty(ARCHIVE_FILE);
        String zipFile$ = archiveFile$;
        File zipFile = new File(zipFile$);
        if (!zipFile.exists())
            zipFile.createNewFile();
        FileOutputStream fos = new FileOutputStream(zipFile$);
        ZipOutputStream zos = new ZipOutputStream(fos);
        ArrayList<File> fl = new ArrayList<File>();
        String entihome$ = entigrator.getEntihome();
        File entihome = new File(entihome$);
        getAllFiles(entihome, fl);
        for (File file : fl) {
            if (!file.isDirectory()) {
                appendToZip(entihome$, file, zos);
            }
        }
        zos.close();
        fos.close();
        return true;
    } catch (Exception e) {
        Logger.getLogger(ArchiveHandler.class.getName()).severe(e.toString());
        return false;
    }
}

From source file:com.taobao.android.tpatch.utils.JarSplitUtils.java

/**
 * jarclass//from  w  w  w  .  j  a  va  2s .c  o  m
 * @param inJar
 * @param removeClasses
 */
public static void removeFilesFromJar(File inJar, List<String> removeClasses) throws IOException {
    if (null == removeClasses || removeClasses.isEmpty()) {
        return;
    }
    File outJar = new File(inJar.getParentFile(), inJar.getName() + ".tmp");
    File outParentFolder = outJar.getParentFile();
    if (!outParentFolder.exists()) {
        outParentFolder.mkdirs();
    }
    FileOutputStream fos = new FileOutputStream(outJar);
    ZipOutputStream jos = new ZipOutputStream(fos);
    final byte[] buffer = new byte[8192];
    FileInputStream fis = new FileInputStream(inJar);
    ZipInputStream zis = new ZipInputStream(fis);

    try {
        // loop on the entries of the jar file package and put them in the final jar
        ZipEntry entry;
        while ((entry = zis.getNextEntry()) != null) {
            // do not take directories or anything inside a potential META-INF folder.
            if (entry.isDirectory() || !entry.getName().endsWith(".class")) {
                continue;
            }
            String name = entry.getName();
            String className = getClassName(name);
            if (removeClasses.contains(className)) {
                continue;
            }
            JarEntry newEntry;
            // Preserve the STORED method of the input entry.
            if (entry.getMethod() == JarEntry.STORED) {
                newEntry = new JarEntry(entry);
            } else {
                // Create a new entry so that the compressed len is recomputed.
                newEntry = new JarEntry(name);
            }
            // add the entry to the jar archive
            jos.putNextEntry(newEntry);

            // read the content of the entry from the input stream, and write it into the archive.
            int count;
            while ((count = zis.read(buffer)) != -1) {
                jos.write(buffer, 0, count);
            }
            // close the entries for this file
            jos.closeEntry();
            zis.closeEntry();
        }
    } finally {
        zis.close();
    }
    fis.close();
    jos.close();
    FileUtils.deleteQuietly(inJar);
    FileUtils.moveFile(outJar, inJar);
}

From source file:it.eng.spagobi.tools.downloadFiles.service.DownloadZipAction.java

public void createZipFromFiles(Vector<File> files, String outputFileName, String folderName)
        throws IOException {
    logger.debug("IN");
    ZipOutputStream out = new ZipOutputStream(new FileOutputStream(outputFileName));
    // Compress the files 
    for (Iterator iterator = files.iterator(); iterator.hasNext();) {
        File file = (File) iterator.next();

        FileInputStream in = new FileInputStream(file);

        String fileName = file.getName();
        // The name to Inssert: remove the parameter folder
        //         int lastIndex=folderName.length();
        //         String fileToInsert=fileName.substring(lastIndex+1);

        logger.debug("Adding to zip entry " + fileName);
        ZipEntry zipEntry = new ZipEntry(fileName);

        // Add ZIP entry to output stream. 
        out.putNextEntry(zipEntry);/*w  ww .  ja va2 s  . c  om*/

        // 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();
        in.close();
    }
    // Complete the ZIP file 
    out.close();
    logger.debug("OUT");
}

From source file:com.joliciel.csvLearner.CSVLearner.java

private void doCommandTrain() throws IOException {
    if (resultFilePath == null)
        throw new RuntimeException("Missing argument: resultFile");
    if (featureDir == null)
        throw new RuntimeException("Missing argument: featureDir");
    if (maxentModelFilePath == null)
        throw new RuntimeException("Missing argument: maxentModel");

    CSVEventListReader reader = this.getReader(TrainingSetType.ALL_TRAINING, false);
    GenericEvents events = reader.getEvents();

    if (generateEventFile) {
        File eventFile = new File(maxentModelFilePath + ".events.txt");
        this.generateEventFile(eventFile, events);
    }/*from ww  w . j  a v  a2  s .co  m*/

    File modelFile = new File(maxentModelFilePath);
    ZipOutputStream zos = new ZipOutputStream(new FileOutputStream(modelFile, false));
    zos.putNextEntry(new ZipEntry(maxentModelBaseName + ".bin"));
    this.train(events, zos);
    zos.flush();

    Writer writer = new BufferedWriter(new OutputStreamWriter(zos));
    zos.putNextEntry(new ZipEntry(maxentModelBaseName + ".nrm_limits.csv"));
    this.writeNormalisationLimits(writer);
    zos.flush();
    zos.close();

    LOG.info("#### Complete ####");
}

From source file:com.esd.ps.EmployerController.java

/**
 * ?zip/*  ww w .j  a  va  2s.  co  m*/
 * 
 * @param list
 * @param packName
 * @param url
 * @return
 */
public int downZIP(List<taskWithBLOBs> list, String packName, String url, int packId) {
    logger.debug("url:{}", packName);
    File zipFile = new File(url + Constants.SLASH + packName);
    if (zipFile.exists()) {
        zipFile.delete();
    }
    try {
        zipFile.createNewFile();
        FileOutputStream fos = new FileOutputStream(zipFile);
        ZipOutputStream zos = new ZipOutputStream(new BufferedOutputStream(fos));

        // writeInZIP(list, zos, Constants.WAV,url);
        writeInZIP(list, zos, Constants.TAG);
        writeInZIP(list, zos, Constants.TEXTGRID);
        if (packId > 0) {
            writeTXTInZIP(zos, url, packId);
        }

        zos.close();// ?,?0kb
        fos.flush();
        fos.close();

    } catch (FileNotFoundException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }
    return 1;
}

From source file:eionet.meta.exports.ods.Ods.java

/**
 * Zips file./*from   w  w w . j av a2  s. co  m*/
 *
 * @param fileToZip
 *            file to zip (full path)
 * @param fileName
 *            file name
 * @throws java.lang.Exception
 *             if operation fails.
 */
private void zip(String fileToZip, String fileName) throws Exception {
    // get source file
    File src = new File(workingFolderPath + ODS_FILE_NAME);
    ZipFile zipFile = new ZipFile(src);
    // create temp file for output
    File tempDst = new File(workingFolderPath + ODS_FILE_NAME + ".zip");
    ZipOutputStream zos = new ZipOutputStream(new FileOutputStream(tempDst));
    // iterate on each entry in zip file
    Enumeration<? extends ZipEntry> entries = zipFile.entries();
    while (entries.hasMoreElements()) {
        ZipEntry zipEntry = entries.nextElement();
        BufferedInputStream bis;
        if (StringUtils.equals(fileName, zipEntry.getName())) {
            bis = new BufferedInputStream(new FileInputStream(new File(fileToZip)));
        } else {
            bis = new BufferedInputStream(zipFile.getInputStream(zipEntry));
        }
        ZipEntry ze = new ZipEntry(zipEntry.getName());
        zos.putNextEntry(ze);

        while (bis.available() > 0) {
            zos.write(bis.read());
        }
        zos.closeEntry();
        bis.close();
    }
    zos.finish();
    zos.close();
    zipFile.close();
    // rename file
    src.delete();
    tempDst.renameTo(src);
}