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: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  .java2s .c  o  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:com.dbi.jmmerge.MapController.java

private void addDirectoryContents(String fullDirPath, File directory, ZipOutputStream zip) throws IOException {
    if (fullDirPath == null)
        fullDirPath = "";
    for (File file : directory.listFiles()) {
        if (file.isDirectory()) {
            if (fullDirPath.length() > 0) {
                addDirectoryContents(fullDirPath + "/" + file.getName(), file, zip);
            } else {
                addDirectoryContents(file.getName(), file, zip);
            }/*from   www . ja va2  s  .  c  o  m*/
        } else {
            String entryName = "";
            if (fullDirPath.length() == 0) {
                entryName = file.getName();
            } else {
                entryName = fullDirPath + "/" + file.getName();
            }

            ZipEntry entry = new ZipEntry(entryName);
            zip.putNextEntry(entry);

            FileInputStream in = new FileInputStream(file);
            IOUtils.copy(in, zip);
            in.close();
            zip.closeEntry();
        }
    }
}

From source file:nl.strohalm.cyclos.themes.ThemeHandlerImpl.java

@Override
protected void doExport(final Theme theme, final OutputStream out) {
    validateForExport(theme);/*from w  w  w  .jav a2  s .c o  m*/
    final ZipOutputStream zipOut = new ZipOutputStream(out);

    final LocalSettings settings = settingsService.getLocalSettings();
    final String charset = settings.getCharset();

    try {
        // Retrieve which files will be exported
        final List<String> exportedFiles = new ArrayList<String>();
        final List<String> exportedImages = new ArrayList<String>();
        final Collection<Style> styles = theme.getStyles();
        if (styles != null) {
            for (final Style style : styles) {
                exportedFiles.addAll(style.getFiles());
            }
        }

        // Store the properties file
        final Properties properties = asProperties(theme);
        zipOut.putNextEntry(new ZipEntry(THEME_PROPERTIES_ENTRY));
        properties.store(zipOut, "");
        zipOut.closeEntry();

        // Store each css file
        final List<File> styleFiles = customizationHelper.listByType(CustomizedFile.Type.STYLE);
        for (File file : styleFiles) {
            // We must use the customized one, not the original
            final String name = file.getName();
            if (!exportedFiles.contains(name)) {
                // When not exporting the given file, continue
                continue;
            }
            // Read the file contents
            file = customizationHelper.findFileOf(CustomizedFile.Type.STYLE, null, name);
            final String contents = FileUtils.readFileToString(file, charset);

            // Resolve the referenced images by reading all url(name) values from the css
            exportedImages.addAll(CSSHelper.resolveURLs(contents));

            // Write the contents to the zip file
            zipOut.putNextEntry(new ZipEntry("styles/" + name));
            IOUtils.copy(new StringReader(contents), zipOut, charset);
            zipOut.closeEntry();
        }

        // Store each image
        final File dir = webImageHelper.imagePath(Image.Nature.STYLE);
        final File[] imageFiles = dir.listFiles(IMAGE_FILTER);
        for (final File file : imageFiles) {
            final String name = file.getName();
            // Export referenced images only
            if (!exportedImages.contains(name)) {
                continue;
            }
            zipOut.putNextEntry(new ZipEntry("images/" + name));
            IOUtils.copy(new FileInputStream(file), zipOut);
            zipOut.closeEntry();
        }

    } catch (final Exception e) {
        throw new ThemeException(e);
    } finally {
        // Close the stream
        IOUtils.closeQuietly(zipOut);
    }
}

From source file:com.webpagebytes.cms.controllers.FlatStorageImporterExporter.java

public void exportParameters(String ownerExternalKey, ZipOutputStream zos, String path) throws WPBIOException {
    try {/*from w  w  w.  ja  va  2  s  .  com*/
        List<WPBParameter> params = dataStorage.query(WPBParameter.class, "ownerExternalKey",
                AdminQueryOperator.EQUAL, ownerExternalKey);
        for (WPBParameter parameter : params) {
            String paramXmlPath = path + parameter.getExternalKey() + "/" + "metadata.xml";
            Map<String, Object> map = new HashMap<String, Object>();
            exporter.export(parameter, map);
            ZipEntry metadataZe = new ZipEntry(paramXmlPath);
            zos.putNextEntry(metadataZe);
            exportToXMLFormat(map, zos);
            zos.closeEntry();
        }

    } catch (IOException e) {
        log.log(Level.SEVERE, e.getMessage(), e);
        throw new WPBIOException("Cannot export parameters for uri's to Zip", e);
    }
}

From source file:fi.mikuz.boarder.util.FileProcessor.java

void zipAddDir(File dirObj, ZipOutputStream out) throws IOException {
    File[] files = dirObj.listFiles();
    byte[] tmpBuf = new byte[1024];

    for (int i = 0; i < files.length; i++) {
        if (files[i].isDirectory()) {
            zipAddDir(files[i], out);//from   ww  w.  j  a  v a  2 s.  c  o m
            continue;
        }
        FileInputStream in = new FileInputStream(files[i].getAbsolutePath());
        System.out.println(" Adding: " + files[i].getAbsolutePath().substring(mBoardDirLength));
        out.putNextEntry(new ZipEntry(files[i].getAbsolutePath().substring(mBoardDirLength)));
        int len;
        while ((len = in.read(tmpBuf)) > 0) {
            out.write(tmpBuf, 0, len);
        }
        out.closeEntry();
        in.close();
    }
}

From source file:it.greenvulcano.util.zip.ZipHelper.java

private void internalZipFile(File srcFile, ZipOutputStream zos, URI base) throws IOException {
    String zipEntryName = base.relativize(srcFile.toURI()).getPath();
    if (srcFile.isDirectory()) {
        zipEntryName = zipEntryName.endsWith("/") ? zipEntryName : zipEntryName + "/";
        ZipEntry anEntry = new ZipEntry(zipEntryName);
        anEntry.setTime(srcFile.lastModified());
        zos.putNextEntry(anEntry);// w ww  . j a va2 s . c o m

        File[] dirList = srcFile.listFiles();
        for (File file : dirList) {
            internalZipFile(file, zos, base);
        }
    } else {
        ZipEntry anEntry = new ZipEntry(zipEntryName);
        anEntry.setTime(srcFile.lastModified());
        zos.putNextEntry(anEntry);

        FileInputStream fis = null;
        try {
            fis = new FileInputStream(srcFile);
            IOUtils.copy(fis, zos);
            zos.closeEntry();
        } finally {
            try {
                if (fis != null) {
                    fis.close();
                }
            } catch (IOException exc) {
                // Do nothing
            }
        }
    }
}

From source file:nl.nn.adapterframework.webcontrol.DumpIbisConsole.java

public void copyServletResponse(ZipOutputStream zipOutputStream, HttpServletRequest request,
        HttpServletResponse response, String resource, String destinationFileName, Set resources, Set linkSet,
        String linkFilter) {/*w ww. jav  a2  s.  c  o  m*/
    long timeStart = new Date().getTime();
    try {
        IbisServletResponseWrapper ibisHttpServletResponseGrabber = new IbisServletResponseWrapper(response);
        RequestDispatcher requestDispatcher = servletContext.getRequestDispatcher(resource);
        requestDispatcher.include(request, ibisHttpServletResponseGrabber);
        String htmlString = ibisHttpServletResponseGrabber.getStringWriter().toString();

        ZipEntry zipEntry = new ZipEntry(destinationFileName);
        //         if (resourceModificationTime!=0) {
        //            zipEntry.setTime(resourceModificationTime);
        //         }

        zipOutputStream.putNextEntry(zipEntry);

        PrintWriter pw = new PrintWriter(zipOutputStream);
        pw.print(htmlString);
        pw.flush();
        zipOutputStream.closeEntry();

        if (!resource.startsWith("FileViewerServlet")) {
            extractResources(resources, htmlString);
        }
        if (linkSet != null) {
            followLinks(linkSet, htmlString, linkFilter);
        }
    } catch (Exception e) {
        log.error("Error copying servletResponse", e);
    }
    long timeEnd = new Date().getTime();
    log.debug("dumped file [" + destinationFileName + "] in " + (timeEnd - timeStart) + " msec.");
}

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

/**
 * jarclass/*  w  ww  .j  ava2  s. c om*/
 * @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:interactivespaces.workbench.project.java.BndOsgiContainerBundleCreator.java

/**
 * Write out the contents of the folder to the distribution file.
 *
 * @param directory// ww  w .  j a  v  a 2  s.c o m
 *          folder being written to the build
 * @param buf
 *          a buffer for caching info
 * @param jarOutputStream
 *          the stream where the jar is being written
 * @param parentPath
 *          path up to this point
 *
 * @throws IOException
 *           for IO access errors
 */
private void writeJarFile(File directory, byte[] buf, ZipOutputStream jarOutputStream, String parentPath)
        throws IOException {
    File[] files = directory.listFiles();
    if (files == null || files.length == 0) {
        log.warn("No source files found in " + directory.getAbsolutePath());
        return;
    }
    for (File file : files) {
        if (file.isDirectory()) {
            writeJarFile(file, buf, jarOutputStream, parentPath + file.getName() + "/");
        } else {
            FileInputStream in = null;
            try {
                in = new FileInputStream(file);

                // Add ZIP entry to output stream.
                jarOutputStream.putNextEntry(new JarEntry(parentPath + file.getName()));

                // Transfer bytes from the file to the ZIP file
                int len;
                while ((len = in.read(buf)) > 0) {
                    jarOutputStream.write(buf, 0, len);
                }

                // Complete the entry
                jarOutputStream.closeEntry();
            } finally {
                fileSupport.close(in, false);
            }
        }
    }
}

From source file:brut.androlib.Androlib.java

private void copyExistingFiles(ZipFile inputFile, ZipOutputStream outputFile) throws IOException {
    // First, copy the contents from the existing outFile:
    Enumeration<? extends ZipEntry> entries = inputFile.entries();
    while (entries.hasMoreElements()) {
        ZipEntry entry = new ZipEntry(entries.nextElement());

        // We can't reuse the compressed size because it depends on compression sizes.
        entry.setCompressedSize(-1);/*w ww  . j a  v a  2  s . co  m*/
        outputFile.putNextEntry(entry);

        // No need to create directory entries in the final apk
        if (!entry.isDirectory()) {
            BrutIO.copy(inputFile, outputFile, entry);
        }

        outputFile.closeEntry();
    }
}