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:edu.stanford.muse.email.JarDocCache.java

@Override
public synchronized void saveHeader(Document d, String prefix, int msgNum)
        throws FileNotFoundException, IOException {
    JarOutputStream jos = getHeadersJarOS(prefix);

    // create the bytes
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    ObjectOutputStream headerOOS = new ObjectOutputStream(baos);
    headerOOS.writeObject(d);//from  w w w .  j a va2  s .  co m
    byte buf[] = baos.toByteArray();

    ZipEntry ze = new ZipEntry(msgNum + ".header");
    ze.setMethod(ZipEntry.DEFLATED);
    jos.putNextEntry(ze);
    jos.write(buf, 0, buf.length);
    jos.closeEntry();
    jos.flush();
}

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 w w .  j ava2 s  .com

        // 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.t3.persistence.PackedFile.java

public void save() throws IOException {
    CodeTimer saveTimer;/*from w  w  w.j av  a 2 s .  com*/

    if (!dirty) {
        return;
    }
    saveTimer = new CodeTimer("PackedFile.save");
    saveTimer.setEnabled(log.isDebugEnabled());

    // Create the new file
    File newFile = new File(tmpDir.getAbsolutePath() + "/" + new GUID() + ".pak");

    try (ZipOutputStream zout = new ZipOutputStream(new BufferedOutputStream(new FileOutputStream(newFile)))) {
        zout.setLevel(1); // fast compression
        saveTimer.start("contentFile");
        if (hasFile(CONTENT_FILE)) {
            zout.putNextEntry(new ZipEntry(CONTENT_FILE));
            try (InputStream is = getFileAsInputStream(CONTENT_FILE)) { // When copying, always use an InputStream
                IOUtils.copy(is, zout);
            }
            zout.closeEntry();
        }
        saveTimer.stop("contentFile");

        saveTimer.start("propertyFile");
        if (getPropertyMap().isEmpty()) {
            removeFile(PROPERTY_FILE);
        } else {
            zout.putNextEntry(new ZipEntry(PROPERTY_FILE));
            Persister.newInstance().toXML(getPropertyMap(), zout);
            zout.closeEntry();
        }
        saveTimer.stop("propertyFile");

        // Now put each file
        saveTimer.start("addFiles");
        addedFileSet.remove(CONTENT_FILE);
        for (String path : addedFileSet) {
            zout.putNextEntry(new ZipEntry(path));
            try (InputStream is = getFileAsInputStream(path)) { // When copying, always use an InputStream
                IOUtils.copy(is, zout);
            }
            zout.closeEntry();
        }
        saveTimer.stop("addFiles");

        // Copy the rest of the zip entries over
        saveTimer.start("copyFiles");
        if (file.exists()) {
            Enumeration<? extends ZipEntry> entries = zFile.entries();
            while (entries.hasMoreElements()) {
                ZipEntry entry = entries.nextElement();
                if (!entry.isDirectory() && !addedFileSet.contains(entry.getName())
                        && !removedFileSet.contains(entry.getName()) && !CONTENT_FILE.equals(entry.getName())
                        && !PROPERTY_FILE.equals(entry.getName())) {
                    zout.putNextEntry(entry);
                    try (InputStream is = getFileAsInputStream(entry.getName())) { // When copying, always use an InputStream
                        IOUtils.copy(is, zout);
                    }
                    zout.closeEntry();
                } else if (entry.isDirectory()) {
                    zout.putNextEntry(entry);
                    zout.closeEntry();
                }
            }
        }
        try {
            if (zFile != null)
                zFile.close();
        } catch (IOException e) {
            // ignore close exception
        }
        zFile = null;
        saveTimer.stop("copyFiles");

        saveTimer.start("close");
        zout.close();
        saveTimer.stop("close");

        // Backup the original
        saveTimer.start("backup");
        File backupFile = new File(tmpDir.getAbsolutePath() + "/" + new GUID() + ".mv");
        if (file.exists()) {
            backupFile.delete(); // Always delete the old backup file first; renameTo() is very platform-dependent
            if (!file.renameTo(backupFile)) {
                FileUtil.copyFile(file, backupFile);
                file.delete();
            }
        }
        saveTimer.stop("backup");

        saveTimer.start("finalize");
        // Finalize
        if (!newFile.renameTo(file))
            FileUtil.copyFile(newFile, file);

        if (backupFile.exists())
            backupFile.delete();
        saveTimer.stop("finalize");

        dirty = false;
    } finally {
        saveTimer.start("cleanup");
        try {
            if (zFile != null)
                zFile.close();
        } catch (IOException e) {
            // ignore close exception
        }
        if (newFile.exists())
            newFile.delete();
        saveTimer.stop("cleanup");

        if (log.isDebugEnabled())
            log.debug(saveTimer);
        saveTimer = null;
    }
}

From source file:de.fu_berlin.inf.dpp.netbeans.feedback.ErrorLogManager.java

/**
 * Convenience wrapper method to upload an error log file to the server. To
 * save time and storage space, the log is compressed to a zip archive with
 * the given zipName.//from  ww w  .j  av  a 2s.c o  m
 * 
 * @param zipName
 *            a name for the zip archive, e.g. with added user ID to make it
 *            unique, zipName must be at least 3 characters long!
 * @throws IOException
 *             if an I/O error occurs
 */
private static void uploadErrorLog(String zipName, File file, IProgressMonitor monitor) throws IOException {

    if (ERROR_LOG_UPLOAD_URL == null) {
        log.warn("error log upload url is not configured, cannot upload error log file");
        return;
    }

    File archive = new File(System.getProperty("java.io.tmpdir"), zipName + ".zip");

    ZipOutputStream out = null;
    FileInputStream in = null;

    byte[] buffer = new byte[8192];

    try {

        in = new FileInputStream(file);

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

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

        int read;

        while ((read = in.read(buffer)) > 0)
            out.write(buffer, 0, read);

        out.finish();
        out.close();

        FileSubmitter.uploadFile(archive, ERROR_LOG_UPLOAD_URL, monitor);
    } finally {
        IOUtils.closeQuietly(out);
        IOUtils.closeQuietly(in);
        archive.delete();
    }
}

From source file:ZipImploder.java

/**
 * process a single file for a .zip file
 * /*w  w w  .jav  a  2s .  c  o m*/
 * @param zos
 * @param f
 * @throws IOException
 */
public void processFile(ZipOutputStream zos, File f) throws IOException {
    String path = f.getCanonicalPath();
    path = path.replace('\\', '/');
    String xpath = removeDrive(removeLead(path));
    ZipEntry ze = new ZipEntry(xpath);
    ze.setTime(f.lastModified());
    ze.setSize(f.length());
    zos.putNextEntry(ze);
    fileCount++;
    try {
        copyFileEntry(zos, f);
    } finally {
        zos.closeEntry();
    }
}

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

/**
 * This function zip the input directory.
 * /*from   w  w  w  .  j a v a  2  s.  co  m*/
 * @param directory
 *            The directory to be zipped.
 * @param base
 *            The base directory.
 * @param out
 *            The zip output stream.
 * @throws IOException
 */
public static void zipDirectory(final File directory, final File base, final ZipOutputStream out)
        throws IOException {

    if (directory != null && base != null && out != null) {
        File[] files = directory.listFiles();
        byte[] buffer = new byte[4096];
        int read = 0;

        FileInputStream in = null;
        ZipEntry entry = null;

        try {
            for (int i = 0, n = files.length; i < n; i++) {
                if (files[i].isDirectory()) {
                    zipDirectory(files[i], base, out);
                } else {
                    in = new FileInputStream(files[i]);
                    entry = new ZipEntry(base.getName().concat("\\")
                            .concat(files[i].getPath().substring(base.getPath().length() + 1)));
                    out.putNextEntry(entry);

                    while (-1 != (read = in.read(buffer))) {
                        out.write(buffer, 0, read);
                    }

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

                    out.closeEntry();

                    in.close();
                    in = null;
                }
            }

        } 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:com.simiacryptus.mindseye.lang.Layer.java

/**
 * Write zip./*from w w  w  . ja va  2s  .  com*/
 *
 * @param out       the out
 * @param precision the precision
 */
default void writeZip(@Nonnull ZipOutputStream out, SerialPrecision precision) {
    try {
        @Nonnull
        HashMap<CharSequence, byte[]> resources = new HashMap<>();
        JsonObject json = getJson(resources, precision);
        out.putNextEntry(new ZipEntry("model.json"));
        @Nonnull
        JsonWriter writer = new JsonWriter(new OutputStreamWriter(out));
        writer.setIndent("  ");
        writer.setHtmlSafe(true);
        writer.setSerializeNulls(false);
        new GsonBuilder().setPrettyPrinting().create().toJson(json, writer);
        writer.flush();
        out.closeEntry();
        resources.forEach((name, data) -> {
            try {
                out.putNextEntry(new ZipEntry(String.valueOf(name)));
                IOUtils.write(data, out);
                out.flush();
                out.closeEntry();
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
        });
    } catch (IOException e) {
        throw new RuntimeException(e);
    }
}

From source file:de.hybris.platform.impex.jalo.ImpExMediasImportTest.java

/**
 * Calls the <code>importData</code> method of given handler with an zip-file path in different formats.
 * /*from  ww  w . j  a v  a 2s  .  co m*/
 * @param handler
 *           handler which will be used for test
 * @param media
 *           media where the data will be imported to
 */
private void mediaImportFromMediasMedia(final MediaDataHandler handler, final Media media,
        final ImpExImportCronJob cronJob) {
    MediaDataHandler myHandler = handler;
    File testFile = null;
    try {
        testFile = File.createTempFile("mediaImportTest", ".zip");
        final ZipOutputStream zos = new ZipOutputStream(new FileOutputStream(testFile));
        zos.putNextEntry(new ZipEntry(new File("notunzip\\notexist.txt").getPath()));
        zos.putNextEntry(new ZipEntry(new File("files\\dummy.txt").getPath()));
        zos.putNextEntry(new ZipEntry(new File("files\\test.txt").getPath()));
        final PrintWriter printer = new PrintWriter(zos);
        printer.print("testest");
        printer.flush();
        zos.flush();
        printer.close();
        zos.close();
    } catch (final IOException e) {
        fail(e.getMessage());
    }
    try {
        final Media mediasMedia = ImpExManager.getInstance().createImpExMedia("mediasMedia", "UTF-8",
                new FileInputStream(testFile));
        cronJob.setMediasMedia(mediasMedia);

        mediaImport(myHandler, media, "files/test.txt", "testest");
        myHandler.cleanUp();
        myHandler = new DefaultCronJobMediaDataHandler(cronJob);
        mediaImport(myHandler, media, "files\\test.txt", "testest");
        myHandler.cleanUp();
        cronJob.setMediasTarget("files");
        myHandler = new DefaultCronJobMediaDataHandler(cronJob);
        mediaImport(myHandler, media, "test.txt", "testest");
        myHandler.cleanUp();
        cronJob.setMediasTarget(null);
    } catch (final Exception e) {
        fail(e.getMessage());
    }
    if (!testFile.delete()) {
        fail("Can not delete temp file: " + testFile.getPath());
    }
}

From source file:com.moss.nomad.core.runner.Runner.java

private MigrationContainer extractContainer(File f) throws Exception {

    ZipFile file = new ZipFile(f);
    ZipEntry entry = new ZipEntry("META-INF/container.xml");
    InputStream in = file.getInputStream(entry);
    Unmarshaller u = context.createUnmarshaller();
    MigrationContainer container = (MigrationContainer) u.unmarshal(in);
    in.close();// ww w  .  j a v  a 2 s.  co  m
    file.close();

    return container;
}

From source file:com.asakusafw.testdriver.compiler.util.DeploymentUtil.java

private static void mergeEntries(ZipOutputStream zip, File file, Set<String> saw) throws IOException {
    try (ZipInputStream in = new ZipInputStream(new BufferedInputStream(new FileInputStream(file)))) {
        while (true) {
            ZipEntry entry = in.getNextEntry();
            if (entry == null) {
                break;
            }/*from   ww  w  .j ava2s  . c  o m*/
            if (saw.contains(entry.getName())) {
                continue;
            }
            if (LOG.isTraceEnabled()) {
                LOG.trace("Copy into archive: {} -> {}", entry.getName(), file);
            }
            saw.add(entry.getName());
            zip.putNextEntry(new ZipEntry(entry.getName()));
            copyStream(in, zip);
        }
    }
}