Example usage for java.util.zip ZipEntry ZipEntry

List of usage examples for java.util.zip ZipEntry ZipEntry

Introduction

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

Prototype

public ZipEntry(ZipEntry e) 

Source Link

Document

Creates a new zip entry with fields taken from the specified zip entry.

Usage

From source file:com.ephesoft.dcma.util.FileUtils.java

/**
 * This method zips the contents of Directory specified into a zip file whose name is provided.
 * /*from  w w w . j  a v a  2  s  . c  om*/
 * @param dir {@link String}
 * @param zipfile {@link String}
 * @param excludeBatchXml boolean
 * @throws IOException 
 * @throws IllegalArgumentException in case of error
 */
public static void zipDirectory(final String dir, final String zipfile, final boolean excludeBatchXml)
        throws IOException, IllegalArgumentException {
    // Check that the directory is a directory, and get its contents
    File directory = new File(dir);
    if (!directory.isDirectory()) {
        throw new IllegalArgumentException("Not a directory:  " + dir);
    }
    String[] entries = directory.list();
    byte[] buffer = new byte[UtilConstants.BUFFER_CONST]; // Create a buffer for copying
    int bytesRead;

    ZipOutputStream out = new ZipOutputStream(new FileOutputStream(zipfile));

    for (int index = 0; index < entries.length; index++) {
        if (excludeBatchXml && entries[index].contains(IUtilCommonConstants.BATCH_XML)) {
            continue;
        }
        File file = new File(directory, entries[index]);
        if (file.isDirectory()) {
            continue;// Ignore directory
        }
        FileInputStream input = new FileInputStream(file); // Stream to read file
        ZipEntry entry = new ZipEntry(file.getName()); // Make a ZipEntry
        out.putNextEntry(entry); // Store entry
        bytesRead = input.read(buffer);
        while (bytesRead != -1) {
            out.write(buffer, 0, bytesRead);
            bytesRead = input.read(buffer);
        }
        if (input != null) {
            input.close();
        }
    }
    if (out != null) {
        out.close();
    }
}

From source file:ch.randelshofer.cubetwister.HTMLExporter.java

public void exportToDirectory(String documentName, DocumentModel model, File dir, ProgressObserver p)
        throws IOException {
    this.documentName = documentName;
    this.model = model;
    this.dir = dir;
    this.zipFile = null;
    this.p = p;/*w w w  . j av a  2s .  c  o  m*/
    init();
    processHTMLTemplates(p);
    new File(dir, "applets").mkdir();
    ZipOutputStream zout = new ZipOutputStream(
            new BufferedOutputStream(new FileOutputStream(new File(dir, "applets/resources.xml.zip"))));
    zout.setLevel(Deflater.BEST_COMPRESSION);
    try {
        //model.writeXML(new PrintWriter(new File(dir, "applets/resources.xml")));
        zout.putNextEntry(new ZipEntry("resources.xml"));
        PrintWriter pw = new PrintWriter(zout);
        model.writeXML(pw);
        pw.flush();
        zout.closeEntry();
    } finally {
        zout.close();
    }
    p.setProgress(p.getProgress() + 1);
}

From source file:com.juancarlosroot.threads.SimulatedUser.java

private String firmarImagen(int fileName) throws IOException {

    String result = "";
    try {//  w w  w .  j  a  v  a  2 s . c  o m
        Path currentRelativePath = Paths.get("");
        String s = currentRelativePath.toAbsolutePath().toString();
        String theFolder = s + "/" + "archivos";

        FileOutputStream fos = new FileOutputStream(userFolderPath + "/" + Integer.toString(fileName) + ".zip");
        ZipOutputStream zos = new ZipOutputStream(fos);

        String file1Name = theFolder + "/" + Integer.toString(fileName) + ".jpg";
        File image = new File(file1Name);

        ZipEntry zipEntry = new ZipEntry(image.getName());
        zos.putNextEntry(zipEntry);
        FileInputStream fileInputStream = new FileInputStream(image);

        byte[] buf = new byte[2048];
        int bytesRead;

        while ((bytesRead = fileInputStream.read(buf)) > 0) {
            zos.write(buf, 0, bytesRead);
        }
        zos.closeEntry();
        zos.close();
        fos.close();

        Path path = Paths.get(userFolderPath + "/" + Integer.toString(fileName) + ".zip");
        byte[] data = Files.readAllBytes(path);
        byte[] byteArray = Base64.encodeBase64(data);
        String b64 = new String(byteArray);

        result = firma(b64, Integer.toString(fileName), "pruebita");
        System.out.println("User : " + idSimulatedUser + " ENVIADO");
        nFilesSend++;

    } catch (FileNotFoundException ex) {
        Logger.getLogger(SimulatedUser.class.getName()).log(Level.SEVERE, null, ex);
    } catch (WriterException_Exception ex) {
        Logger.getLogger(SimulatedUser.class.getName()).log(Level.SEVERE, null, ex);
    } catch (IOException_Exception ex) {
        Logger.getLogger(SimulatedUser.class.getName()).log(Level.SEVERE, null, ex);
    } catch (NoSuchAlgorithmException_Exception ex) {
        Logger.getLogger(SimulatedUser.class.getName()).log(Level.SEVERE, null, ex);
    } catch (InterruptedException_Exception ex) {
        Logger.getLogger(SimulatedUser.class.getName()).log(Level.SEVERE, null, ex);
    }

    return "http://" + result;
}

From source file:de.brendamour.jpasskit.signing.PKInMemorySigningUtil.java

private byte[] createZippedPassAndReturnAsByteArray(final Map<String, ByteBuffer> files)
        throws PKSigningException {
    ByteArrayOutputStream byteArrayOutputStreamForZippedPass = null;
    ZipOutputStream zipOutputStream = null;
    byteArrayOutputStreamForZippedPass = new ByteArrayOutputStream();
    zipOutputStream = new ZipOutputStream(byteArrayOutputStreamForZippedPass);
    for (Entry<String, ByteBuffer> passResourceFile : files.entrySet()) {
        ZipEntry entry = new ZipEntry(getRelativePathOfZipEntry(passResourceFile.getKey(), ""));
        try {//w  ww .ja  v a  2s  . co m
            zipOutputStream.putNextEntry(entry);
            IOUtils.copy(new ByteArrayInputStream(passResourceFile.getValue().array()), zipOutputStream);
        } catch (IOException e) {
            IOUtils.closeQuietly(zipOutputStream);
            throw new PKSigningException("Error when zipping file", e);
        }
    }
    IOUtils.closeQuietly(zipOutputStream);
    return byteArrayOutputStreamForZippedPass.toByteArray();
}

From source file:com.seleniumtests.util.FileUtility.java

/**
 * Create a zip file from list of files to a temp directory. They will be added at the root of zip file
 * @param files// ww w.  ja  va 2 s  .  c  om
 * @return the zipped file
 * @throws IOException
 */
public static File createZipArchiveFromFiles(List<File> files) throws IOException {
    final File zipArchive = File.createTempFile("temp_zip_", ".zip");
    try (final ZipOutputStream out = new ZipOutputStream(new FileOutputStream(zipArchive))) {
        for (File f : files) {
            if (!f.exists()) {
                logger.warn(String.format("File %s does not exist", f.getName()));
                continue;
            }
            ZipEntry e = new ZipEntry(f.getName());
            out.putNextEntry(e);
            IOUtils.write(FileUtils.readFileToByteArray(f), out);
            out.closeEntry();
        }
    }
    return zipArchive;
}

From source file:edu.umd.cs.marmoset.modelClasses.ZipFileAggregator.java

/**
 * Adds a zipfile from an inputStream to the aggregate zipfile.
 *
 * @param dirName name of the top-level directory that will be
 * @param inputStream the inputStream to the zipfile created in the aggregate zip file
 * @throws IOException//from   w  w w. ja  v a 2s.c  o  m
 * @throws BadInputZipFileException
 */
private void addZipFileFromInputStream(String dirName, long time, InputStream inputStream)
        throws IOException, BadInputZipFileException {
    // First pass: just scan through the contents of the
    // input file to make sure it's really valid.
    ZipInputStream zipInput = null;
    try {
        zipInput = new ZipInputStream(new BufferedInputStream(inputStream));
        ZipEntry entry;
        while ((entry = zipInput.getNextEntry()) != null) {
            zipInput.closeEntry();
        }
    } catch (IOException e) {
        throw new BadInputZipFileException("Input zip file seems to be invalid", e);
    } finally {
        if (zipInput != null)
            zipInput.close();
    }

    // FIXME: It is probably wrong to call reset() on any input stream; for my application the inputStream will only ByteArrayInputStream or FileInputStream
    inputStream.reset();

    // Second pass: read each entry from the input zip file,
    // writing it to the output file.
    zipInput = null;
    try {
        // add the root directory with the correct timestamp
        if (time > 0L) {
            // Create output entry
            ZipEntry outputEntry = new ZipEntry(dirName + "/");
            outputEntry.setTime(time);
            zipOutput.closeEntry();
        }

        zipInput = new ZipInputStream(new BufferedInputStream(inputStream));
        ZipEntry entry;
        while ((entry = zipInput.getNextEntry()) != null) {
            try {
                String name = entry.getName();
                // Convert absolute paths to relative
                if (name.startsWith("/")) {
                    name = name.substring(1);
                }

                // Prepend directory name
                name = dirName + "/" + name;

                // Create output entry
                ZipEntry outputEntry = new ZipEntry(name);
                if (time > 0L)
                    outputEntry.setTime(time);
                zipOutput.putNextEntry(outputEntry);

                // Copy zip input to output
                CopyUtils.copy(zipInput, zipOutput);
            } catch (Exception zex) {
                // ignore it
            } finally {
                zipInput.closeEntry();
                zipOutput.closeEntry();
            }
        }
    } finally {
        if (zipInput != null) {
            try {
                zipInput.close();
            } catch (IOException ignore) {
                // Ignore
            }
        }
    }
}

From source file:com.permeance.utility.scriptinghelper.portlets.ScriptingHelperPortlet.java

@Override
public void serveResource(ResourceRequest resourceRequest, ResourceResponse resourceResponse) {
    ZipOutputStream zout = null;/*from   ww  w  .  j  a  va  2 s.  c om*/
    OutputStream out = null;
    try {
        sCheckPermissions(resourceRequest);
        _log.info("Export All As Zip");

        Map<String, String> savedscripts = new TreeMap<String, String>();
        PortletPreferences prefs = resourceRequest.getPreferences();
        for (String prefName : prefs.getMap().keySet()) {
            if (prefName != null && prefName.startsWith("savedscript.")) {
                String scriptName = prefName.substring("savedscript.".length());
                String script = prefs.getValue(prefName, "");
                String lang = prefs.getValue("lang." + scriptName, getDefaultLanguage());
                savedscripts.put(scriptName + "." + lang, script);
            }
        }

        String filename = "liferay-scripts.zip";

        out = resourceResponse.getPortletOutputStream();
        zout = new ZipOutputStream(out);
        for (String key : savedscripts.keySet()) {
            String value = savedscripts.get(key);
            zout.putNextEntry(new ZipEntry(key));
            zout.write(value.getBytes("utf-8"));
        }
        resourceResponse.setContentType("application/zip");
        resourceResponse.addProperty(HttpHeaders.CACHE_CONTROL, "max-age=3600, must-revalidate");
        resourceResponse.addProperty(HttpHeaders.CONTENT_DISPOSITION, "filename=" + filename);

    } catch (Exception e) {
        _log.error(e);
    } finally {
        try {
            if (zout != null) {
                zout.close();
            }
        } catch (Exception e) {
        }
        try {
            if (out != null) {
                out.close();
            }
        } catch (Exception e) {
        }
    }
}

From source file:com.dangdang.config.service.web.mb.PropertyExportManagedBean.java

/**
 * ??ZIP/*from www  .  j av  a 2 s. com*/
 * 
 * @return
 */
public StreamedContent generateFileAll() {
    LOGGER.info("Export all config group");
    StreamedContent file = null;

    String authedNode = ZKPaths.makePath(nodeAuth.getAuthedNode(), versionMB.getSelectedVersion());
    List<String> children = nodeService.listChildren(authedNode);
    if (children != null && !children.isEmpty()) {
        try {
            ByteArrayOutputStream out = new ByteArrayOutputStream();
            ZipOutputStream zipOutputStream = new ZipOutputStream(out);
            for (String groupName : children) {
                String groupPath = ZKPaths.makePath(authedNode, groupName);
                String fileName = ZKPaths.getNodeFromPath(groupPath) + ".properties";

                List<PropertyItemVO> items = nodeBusiness.findPropertyItems(nodeAuth.getAuthedNode(),
                        versionMB.getSelectedVersion(), groupName);
                List<String> lines = formatPropertyLines(groupName, items);
                if (!lines.isEmpty()) {
                    ZipEntry zipEntry = new ZipEntry(fileName);
                    zipOutputStream.putNextEntry(zipEntry);
                    IOUtils.writeLines(lines, "\r\n", zipOutputStream, Charsets.UTF_8.displayName());
                    zipOutputStream.closeEntry();
                }
            }

            zipOutputStream.close();
            byte[] data = out.toByteArray();
            InputStream in = new ByteArrayInputStream(data);

            String fileName = authedNode.replace('/', '-') + ".zip";
            file = new DefaultStreamedContent(in, "application/zip", fileName, Charsets.UTF_8.name());
        } catch (IOException e) {
            LOGGER.error(e.getMessage(), e);
        }
    }

    return file;
}

From source file:org.openmrs.module.omodexport.util.OmodExportUtil.java

/**
 * Utility method for zipping a list of files
 * //from  w w w . ja va2s  .  c  o m
 * @param files -The list of files to zip
 * @param out
 * @throws FileNotFoundException
 * @throws IOException
 */
public static void zipFiles(List<File> files, ZipOutputStream out) throws FileNotFoundException, IOException {
    byte[] buffer = new byte[4096]; // Create a buffer for copying
    int bytesRead;

    for (File f : files) {
        if (f.isDirectory())
            continue;// Ignore directory
        FileInputStream in = new FileInputStream(f); // Stream to read file
        out.putNextEntry(new ZipEntry(f.getName())); // Store entry
        while ((bytesRead = in.read(buffer)) != -1)
            out.write(buffer, 0, bytesRead);
        in.close();
    }

    out.close();
}

From source file:com.flexive.core.storage.GenericDivisionExporter.java

/**
 * Dump a single file to a zip output stream
 *
 * @param zip  zip output stream/*from   www  . j a  v  a2 s .co  m*/
 * @param file the file to dump
 * @param path absolute base directory path (will be stripped in the archive from file)
 * @throws IOException on errors
 */
private void dumpFile(ZipOutputStream zip, File file, String path) throws IOException {
    if (file.isDirectory()) {
        for (File f : file.listFiles())
            dumpFile(zip, f, path);
        return;
    }
    ZipEntry ze = new ZipEntry(FOLDER_FS_BINARY + file.getAbsolutePath().substring(path.length()));
    zip.putNextEntry(ze);
    FileInputStream fis = null;
    try {
        fis = new FileInputStream(file);
        byte[] buffer = new byte[4096];
        int read;
        while ((read = fis.read(buffer)) != -1)
            zip.write(buffer, 0, read);
    } finally {
        if (fis != null)
            fis.close();
    }
    zip.closeEntry();
    zip.flush();
}