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:net.sourceforge.tagsea.instrumentation.network.NetworkSendJob.java

private File compressLogs(File[] filesToCompress) throws IOException {
    IPath stateLocation = TagSEAInstrumentationPlugin.getDefault().getStateLocation();
    DateFormat format = DateUtils.getDateFormat();
    String sendName = format.format(new Date()).replace('/', '-') + "-workspace"
            + stateLocation.toPortableString().hashCode() + ".zip";
    File sendFile = stateLocation.append(sendName).toFile();
    if (!sendFile.exists()) {
        sendFile.createNewFile();/*  w ww.  j a va  2 s .c  o m*/
    }
    if (filesToCompress.length == 0) {
        sendFile.delete();
        return null;
    }
    ZipOutputStream zipStream;
    zipStream = new ZipOutputStream(new FileOutputStream(sendFile));

    for (File file : filesToCompress) {
        FileInputStream inputStream = null;
        try {
            ZipEntry entry = new ZipEntry(file.getName());
            zipStream.putNextEntry(entry);
            inputStream = new FileInputStream(file);
            byte[] buffer = new byte[1024];
            int read = -1;
            while ((read = inputStream.read(buffer)) != -1) {
                zipStream.write(buffer, 0, read);
            }

            zipStream.closeEntry();
        } finally {
            if (inputStream != null) {
                inputStream.close();
            }
        }
    }
    zipStream.close();
    return sendFile;
}

From source file:it.isislab.sof.core.engine.hadoop.sshclient.connection.SofManager.java

private static void addDir(File dirObj, ZipOutputStream out, String dirToZip) throws IOException {
    File[] files = dirObj.listFiles();
    byte[] tmpBuf = new byte[1024];

    for (int i = 0; i < files.length; i++) {
        if (files[i].isDirectory()) {
            addDir(files[i], out, dirToZip);
            continue;
        }//from  ww w  .  j a  v  a 2s  . co m

        FileInputStream in = new FileInputStream(files[i].getAbsolutePath());
        System.out.println("Zipping: " + files[i].getName());
        String filename = files[i].getAbsolutePath().substring(dirToZip.length());
        out.putNextEntry(new ZipEntry(filename));
        int len;
        while ((len = in.read(tmpBuf)) > 0) {
            out.write(tmpBuf, 0, len);
        }
        out.closeEntry();
        in.close();
    }
}

From source file:edu.harvard.iq.dvn.core.analysis.NetworkDataServiceBean.java

private void addZipEntry(ZipOutputStream zout, String inputFileName, String outputFileName) throws IOException {
    FileInputStream tmpin = new FileInputStream(inputFileName);
    byte[] dataBuffer = new byte[8192];
    int i = 0;//from   w  w  w  .ja v a  2s . co m

    ZipEntry e = new ZipEntry(outputFileName);
    zout.putNextEntry(e);

    while ((i = tmpin.read(dataBuffer)) > 0) {
        zout.write(dataBuffer, 0, i);
        zout.flush();
    }
    tmpin.close();
    zout.closeEntry();
}

From source file:com.genericworkflownodes.knime.workflowexporter.export.impl.GuseKnimeWorkflowExporter.java

@Override
public void export(final Workflow workflow, final File destination) throws Exception {
    if (LOGGER.isDebugEnabled()) {
        LOGGER.debug(/*from www. j a  va 2  s  . c  o m*/
                "exporting using " + getShortDescription() + " to [" + destination.getAbsolutePath() + "]");
    }
    final StringBuilder builder = new StringBuilder();
    generateWorkflowXml(workflow, builder);

    final ZipOutputStream zipOutputStream = new ZipOutputStream(new FileOutputStream(destination));
    zipOutputStream.putNextEntry(new ZipEntry("workflow.xml"));

    zipOutputStream.write(formatXml(builder.toString()).getBytes());

    zipOutputStream.closeEntry();
    zipOutputStream.close();
}

From source file:com.sangupta.jerry.util.ZipUtils.java

/**
 * Compresses the provided file into ZIP format adding a '.ZIP' at the end
 * of the filename.//from www  .  j  a  v  a 2s.c o m
 * 
 * @param filePath
 *            the file path that needs to be compressed
 * 
 * @return returns the absolute path of the ZIP file.
 */
public String createZipFile(String filePath) {
    LOGGER.debug("Starting compression of " + filePath);

    String zipFilename = filePath + ".zip";
    LOGGER.debug("Creating zip file at " + zipFilename);

    byte[] buf = new byte[1024];

    ZipOutputStream stream = null;
    FileInputStream input = null;
    try {
        // Create the ZIP file
        stream = new ZipOutputStream(new FileOutputStream(zipFilename));

        // Compress the file
        File file = new File(filePath);
        input = new FileInputStream(file);

        // Add ZIP entry to output stream.
        stream.putNextEntry(new ZipEntry(file.getName()));

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

        // Complete the entry
        stream.closeEntry();
    } catch (IOException e) {
        LOGGER.error("Unable to compress file " + filePath, e);
    } finally {
        IOUtils.closeQuietly(input);

        // Complete the ZIP file
        IOUtils.closeQuietly(stream);
    }

    return zipFilename;
}

From source file:edu.jhuapl.graphs.controller.GraphController.java

public static String zipGraphs(List<GraphObject> graphs, String tempDir, String userId) throws GraphException {
    if (graphs != null && graphs.size() > 0) {
        byte[] byteBuffer = new byte[1024];
        String zipFileName = getUniqueId(userId) + ".zip";

        try {/*from  w ww  .  j av  a  2 s.co m*/
            File zipFile = new File(tempDir, zipFileName);
            ZipOutputStream zos = new ZipOutputStream(new FileOutputStream(zipFile));
            boolean hasGraphs = false;

            for (GraphObject graph : graphs) {
                if (graph != null) {
                    byte[] renderedGraph = graph.getRenderedGraph().getData();
                    ByteArrayInputStream in = new ByteArrayInputStream(renderedGraph);
                    int len;

                    zos.putNextEntry(new ZipEntry(graph.getImageFileName()));

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

                    in.close();
                    zos.closeEntry();
                    hasGraphs = true;
                }
            }

            zos.close();

            if (hasGraphs) {
                return zipFileName;
            } else {
                return null;
            }
        } catch (IOException e) {
            throw new GraphException("Could not write zip", e);
        }
    }

    return null;
}

From source file:com.qwazr.library.archiver.ArchiverTool.java

public void addToZipFile(final String entryName, final String filePath, final ZipOutputStream zos)
        throws IOException {
    final Path srcFile = Paths.get(filePath);
    if (!Files.exists(srcFile))
        throw new FileNotFoundException("The file does not exists: " + srcFile.toAbsolutePath());
    try (final InputStream in = Files.newInputStream(srcFile);
            final BufferedInputStream bIn = new BufferedInputStream(in)) {
        ZipEntry zipEntry = new ZipEntry(entryName);
        zos.putNextEntry(zipEntry);/*from www .  ja  va2 s.c  om*/
        IOUtils.copy(bIn, zos);
        zos.closeEntry();
    }
}

From source file:de.jwi.zip.Zipper.java

public void zip(ZipOutputStream out, File f, File base) throws IOException {
    String name = f.getPath().replace('\\', '/');

    if (base != null) {
        String basename = base.getPath().replace('\\', '/');

        if (name.startsWith(basename)) {
            name = name.substring(basename.length());
        }/*  ww  w .  j a  v a  2 s. com*/
    }

    if (name.startsWith("/")) {
        name = name.substring(1);
    }

    ZipEntry entry = new ZipEntry(name);
    entry.setTime(f.lastModified());

    out.putNextEntry(entry);

    FileInputStream is = new FileInputStream(f);

    byte[] buf = new byte[BUFSIZE];

    try {
        int l;
        while ((l = is.read(buf)) > -1) {
            out.write(buf, 0, l);
        }
    } finally {
        is.close();
    }
    out.closeEntry();

}

From source file:net.sourceforge.dita4publishers.tools.dxp.DitaDxpHelper.java

/**
 * Given a DITA map bounded object set, zips it up into a DXP Zip package.
 * @param mapBos/*from   w ww .  j av a 2s.  com*/
 * @param outputZipFile
 * @throws Exception 
 */
public static void zipMapBos(DitaBoundedObjectSet mapBos, File outputZipFile, MapBosProcessorOptions options)
        throws Exception {
    /*
     *  Some potential complexities:
     *  
     *  - DXP package spec requires either a map manifest or that 
     *  there be exactly one map at the root of the zip package. This 
     *  means that the file structure of the BOS needs to be checked to
     *  see if the files already conform to this structure and, if not,
     *  they need to be reorganized and have pointers rewritten if a 
     *  map manifest has not been requested.
     *  
     *  - If the file structure of the original data includes files not
     *  below the root map, the file organization must be reworked whether
     *  or not a map manifest has been requested.
     *  
     *  - Need to generate DXP map manifest if a manifest is requested.
     *  
     *  - If user has requested that the original file structure be 
     *  remembered, a manifest must be generated.
     */

    log.debug("Determining zip file organization...");

    BosVisitor visitor = new DxpFileOrganizingBosVisitor();
    visitor.visit(mapBos);

    if (!options.isQuiet())
        log.info("Creating DXP package \"" + outputZipFile.getAbsolutePath() + "\"...");
    OutputStream outStream = new FileOutputStream(outputZipFile);
    ZipOutputStream zipOutStream = new ZipOutputStream(outStream);

    ZipEntry entry = null;

    // At this point, URIs of all members should reflect their
    // storage location within the resulting DXP package. There
    // must also be a root map, either the original map
    // we started with or a DXP manifest map.

    URI rootMapUri = mapBos.getRoot().getEffectiveUri();
    URI baseUri = null;
    try {
        baseUri = AddressingUtil.getParent(rootMapUri);
    } catch (URISyntaxException e) {
        throw new BosException("URI syntax exception getting parent URI: " + e.getMessage());
    }

    Set<String> dirs = new HashSet<String>();

    if (!options.isQuiet())
        log.info("Constructing DXP package...");
    for (BosMember member : mapBos.getMembers()) {
        if (!options.isQuiet())
            log.info("Adding member " + member + " to zip...");
        URI relativeUri = baseUri.relativize(member.getEffectiveUri());
        File temp = new File(relativeUri.getPath());
        String parentPath = temp.getParent();
        if (parentPath != null && !"".equals(parentPath) && !parentPath.endsWith("/")) {
            parentPath += "/";
        }
        log.debug("parentPath=\"" + parentPath + "\"");
        if (!"".equals(parentPath) && parentPath != null && !dirs.contains(parentPath)) {
            entry = new ZipEntry(parentPath);
            zipOutStream.putNextEntry(entry);
            zipOutStream.closeEntry();
            dirs.add(parentPath);
        }
        entry = new ZipEntry(relativeUri.getPath());
        zipOutStream.putNextEntry(entry);
        IOUtils.copy(member.getInputStream(), zipOutStream);
        zipOutStream.closeEntry();
    }

    zipOutStream.close();
    if (!options.isQuiet())
        log.info("DXP package \"" + outputZipFile.getAbsolutePath() + "\" created.");
}

From source file:org.apache.sling.oakui.OakUIWebConsole.java

private void downloadSegment(@Nonnull HttpServletRequest request, @Nonnull HttpServletResponse response,
        @Nonnull String index, @Nonnull String file) throws IOException {
    NodeStore ns = getNodeStore();/*  w  ww  .  j a  va2s  .c  o  m*/
    NodeState oakIndex = ns.getRoot().getChildNode("oak:index");
    NodeStoreDirectory nsDirectory = new NodeStoreDirectory(oakIndex, index);

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

    ZipOutputStream zipOutputStream = new ZipOutputStream(response.getOutputStream());
    for (String f : nsDirectory.listAll()) {
        ZipEntry ze = new ZipEntry(f);
        ze.setSize(nsDirectory.fileLength(f));
        ze.setTime(nsDirectory.getLastModified(f));
        zipOutputStream.putNextEntry(ze);
        OakIndexInput input = nsDirectory.openInput(f);
        transferBytes(input, zipOutputStream);
        zipOutputStream.closeEntry();
    }
    zipOutputStream.finish();
}