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:jeffaschenk.tomcat.instance.generator.builders.TomcatInstanceBuilderHelper.java

/**
 * Zip File into Archive/*from w w w .  j ava 2s  .co  m*/
 *
 * @param GENERATION_LOGGER Reference
 * @param zipFilePath       Zip file Destination.
 * @param fileFolder        Folder to be zipped Up ...
 * @throws IOException
 */
protected static boolean zipFile(GenerationLogger GENERATION_LOGGER, String zipFilePath, String fileFolder)
        throws IOException {
    /**
     * First get All Nodes with Folder
     */
    List<String> fileList = new ArrayList<>();
    generateFileListForCompression(new File(fileFolder), fileList);
    File sourceFolder = new File(fileFolder);
    byte[] buffer = new byte[8192];
    try {
        FileOutputStream fos = new FileOutputStream(zipFilePath);
        ZipOutputStream zos = new ZipOutputStream(fos);

        GENERATION_LOGGER.info("Compressing Instance Generation to Zip: " + zipFilePath);
        /**
         * Loop Over Files
         */
        for (String filename : fileList) {
            String zipEntryName = filename.substring(sourceFolder.getParent().length() + 1, filename.length());
            ZipEntry ze = new ZipEntry(zipEntryName);
            zos.putNextEntry(ze);
            FileInputStream in = new FileInputStream(filename);
            int len;
            while ((len = in.read(buffer)) > 0) {
                zos.write(buffer, 0, len);
            }
            in.close();
            GENERATION_LOGGER.debug("File Added to Archive: " + zipEntryName);
        }
        /**
         * Close
         */
        zos.closeEntry();
        zos.close();
        return true;
    } catch (IOException ex) {
        GENERATION_LOGGER.error(ex.getMessage());
        ex.printStackTrace();
        return false;
    }
}

From source file:com.hazelcast.stabilizer.Utils.java

public static byte[] zip(List<File> roots) throws IOException {
    ByteArrayOutputStream out = new ByteArrayOutputStream();
    Deque<File> queue = new LinkedList<File>();
    ZipOutputStream zout = new ZipOutputStream(out);

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

    try {//from   w ww. j a va 2s.c o  m
        for (File root : roots) {
            URI base = root.isDirectory() ? root.toURI() : root.getParentFile().toURI();
            queue.push(root);
            while (!queue.isEmpty()) {
                File file = queue.pop();
                if (file.getName().equals(".DS_Store")) {
                    continue;
                }

                //                    log.finest("Zipping: " + file.getAbsolutePath());

                if (file.isDirectory()) {
                    String name = base.relativize(file.toURI()).getPath();
                    name = name.endsWith("/") ? name : name + "/";

                    if (names.add(name)) {
                        zout.putNextEntry(new ZipEntry(name));
                    }

                    for (File kid : file.listFiles()) {
                        queue.push(kid);
                    }
                } else {
                    String name = base.relativize(file.toURI()).getPath();
                    zout.putNextEntry(new ZipEntry(name));
                    copy(file, zout);
                    zout.closeEntry();
                }
            }
        }
    } finally {
        zout.close();
    }

    return out.toByteArray();
}

From source file:com.mgmtp.jfunk.core.scripting.ModuleArchiver.java

private void zip(final String prefix, final File file, final ZipOutputStream zipOut) throws IOException {
    if (file.isDirectory()) {
        String recursePrefix = prefix + file.getName() + '/';
        for (File child : file.listFiles()) {
            zip(recursePrefix, child, zipOut);
        }//from   w  w w  . ja v a2  s .com
    } else {
        FileInputStream in = null;
        try {
            in = new FileInputStream(file);
            zipOut.putNextEntry(new ZipEntry(prefix + file.getName()));
            copy(in, zipOut);
        } finally {
            closeQuietly(in);
            zipOut.flush();
            zipOut.closeEntry();
        }
    }
}

From source file:org.agnitas.util.ZipUtilities.java

/**
 * Compress a file or recursively compress all files of a folder.
 * /*from  w w  w .  j a va 2  s . c o m*/
 * @param sourceFile
 * @param destinationZipFileSream
 * @throws IOException
 */
public static void addFileToOpenZipFileStream(File sourceFile, String relativeDirPath,
        ZipOutputStream destinationZipFileSream) throws IOException {
    BufferedInputStream bufferedFileInputStream = null;

    if (!sourceFile.exists())
        throw new IOException("SourceFile does not exist");

    if (destinationZipFileSream == null)
        throw new IOException("DestinationStream is not ready");

    if (relativeDirPath == null || (!relativeDirPath.endsWith("/") && !relativeDirPath.endsWith("\\")))
        throw new IOException("RelativeDirPath is invalid");

    try {
        if (!sourceFile.isDirectory()) {
            ZipEntry entry = new ZipEntry(relativeDirPath + sourceFile.getName());
            entry.setTime(sourceFile.lastModified());
            destinationZipFileSream.putNextEntry(entry);

            bufferedFileInputStream = new BufferedInputStream(new FileInputStream(sourceFile));
            byte[] bufferArray = new byte[1024];
            int byteBufferFillLength = bufferedFileInputStream.read(bufferArray);
            while (byteBufferFillLength > -1) {
                destinationZipFileSream.write(bufferArray, 0, byteBufferFillLength);
                byteBufferFillLength = bufferedFileInputStream.read(bufferArray);
            }
            bufferedFileInputStream.close();
            bufferedFileInputStream = null;

            destinationZipFileSream.flush();
            destinationZipFileSream.closeEntry();
        } else {
            for (File sourceSubFile : sourceFile.listFiles()) {
                addFileToOpenZipFileStream(sourceSubFile,
                        relativeDirPath + sourceFile.getName() + File.separator, destinationZipFileSream);
            }
        }
    } catch (IOException e) {
        throw e;
    } finally {
        if (bufferedFileInputStream != null) {
            try {
                bufferedFileInputStream.close();
            } catch (Exception e) {
            }
            bufferedFileInputStream = null;
        }
    }
}

From source file:de.unisaarland.swan.export.ExportUtil.java

private void marshalScheme(Project proj, ZipOutputStream zos) throws IOException {
    final Scheme schemeOrig = proj.getScheme();
    final de.unisaarland.swan.export.model.xml.scheme.Scheme schemeExport = (de.unisaarland.swan.export.model.xml.scheme.Scheme) mapperFacade
            .map(schemeOrig, SCHEME_EXPORT_CLASS);

    String fileName = schemeExport.getName() + ".xml";
    File schemefile = new File(fileName);

    marshalXMLToSingleFile(schemeExport, schemefile);

    zos.putNextEntry(new ZipEntry(fileName));
    zos.write(FileUtils.readFileToByteArray(schemefile));
    zos.closeEntry();
}

From source file:fr.gael.dhus.datastore.FileSystemDataStore.java

/**
 * Generates a zip file./*from   w ww  .ja  v a  2s . co m*/
 *
 * @param source      source file or directory to compress.
 * @param destination destination of zipped file.
 * @return the zipped file.
 */
private void generateZip(File source, File destination) throws IOException {
    if (source == null || !source.exists()) {
        throw new IllegalArgumentException("source file should exist");
    }
    if (destination == null) {
        throw new IllegalArgumentException("destination file should be not null");
    }

    FileOutputStream output = new FileOutputStream(destination);
    ZipOutputStream zip_out = new ZipOutputStream(output);
    zip_out.setLevel(cfgManager.getDownloadConfiguration().getCompressionLevel());

    List<QualifiedFile> file_list = getFileList(source);
    byte[] buffer = new byte[BUFFER_SIZE];
    for (QualifiedFile qualified_file : file_list) {
        ZipEntry entry = new ZipEntry(qualified_file.getQualifier());
        InputStream input = new FileInputStream(qualified_file.getFile());

        int read;
        zip_out.putNextEntry(entry);
        while ((read = input.read(buffer)) != -1) {
            zip_out.write(buffer, 0, read);
        }
        input.close();
        zip_out.closeEntry();
    }
    zip_out.close();
    output.close();
}

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

/**
 * Signal the end of a zip entry and flush the stream
 *
 * @param out zip output stream/* www . jav  a  2 s.c  o m*/
 * @throws IOException on errors
 */
private void endEntry(ZipOutputStream out) throws IOException {
    out.closeEntry();
    out.flush();
}

From source file:com.yifanlu.PSXperiaTool.ZpakCreate.java

public void create(boolean noCompress) throws IOException {
    Logger.info("Generating zpak file from directory %s with compression = %b", mDirectory.getPath(),
            !noCompress);//from w ww .jav  a 2 s  .com
    IOFileFilter filter = new IOFileFilter() {
        public boolean accept(File file) {
            if (file.getName().startsWith(".")) {
                Logger.debug("Skipping file %s", file.getPath());
                return false;
            }
            return true;
        }

        public boolean accept(File file, String s) {
            if (s.startsWith(".")) {
                Logger.debug("Skipping file %s", file.getPath());
                return false;
            }
            return true;
        }
    };
    Iterator<File> it = FileUtils.iterateFiles(mDirectory, filter, TrueFileFilter.INSTANCE);
    ZipOutputStream out = new ZipOutputStream(mOut);
    out.setMethod(noCompress ? ZipEntry.STORED : ZipEntry.DEFLATED);
    while (it.hasNext()) {
        File current = it.next();
        FileInputStream in = new FileInputStream(current);
        ZipEntry zEntry = new ZipEntry(
                current.getPath().replace(mDirectory.getPath(), "").substring(1).replace("\\", "/"));
        if (noCompress) {
            zEntry.setSize(in.getChannel().size());
            zEntry.setCompressedSize(in.getChannel().size());
            zEntry.setCrc(getCRC32(current));
        }
        out.putNextEntry(zEntry);
        Logger.verbose("Adding file %s", current.getPath());
        int n;
        while ((n = in.read(mBuffer)) != -1) {
            out.write(mBuffer, 0, n);
        }
        in.close();
        out.closeEntry();
    }
    out.close();
    Logger.debug("Done with ZPAK creation.");
}

From source file:com.pr7.logging.CustomDailyRollingFileAppender.java

/**
 * Compresses the passed file to a .zip file, stores the .zip in the same
 * directory as the passed file, and then deletes the original, leaving only
 * the .zipped archive./*ww w .j  ava2s  . c  o  m*/
 * 
 * @param file
 */
private void zipAndDelete(File file) throws IOException {
    if (!file.getName().endsWith(".zip")) {
        System.out.println("zipAndDelete file = " + file.getName());
        String folderName = "archive";
        File folder = new File(file.getParent(), folderName);
        if (!folder.exists()) {
            if (folder.mkdir()) {
                System.out.println("Create " + folderName + " success.");
            } else {
                System.out.println("Create " + folderName + " failed.");
            }
        }

        File zipFile = new File(folder, file.getName() + ".zip");
        FileInputStream fis = new FileInputStream(file);
        FileOutputStream fos = new FileOutputStream(zipFile);
        ZipOutputStream zos = new ZipOutputStream(fos);
        ZipEntry zipEntry = new ZipEntry(file.getName());
        zos.putNextEntry(zipEntry);

        byte[] buffer = new byte[4096];
        while (true) {
            int bytesRead = fis.read(buffer);
            if (bytesRead == -1)
                break;
            else {
                zos.write(buffer, 0, bytesRead);
            }
        }
        zos.closeEntry();
        fis.close();
        zos.close();
        file.delete();
    }
}

From source file:dk.itst.oiosaml.sp.configuration.ConfigurationHandler.java

protected File generateZipFile(final String contextPath, final String password, byte[] idpMetadata,
        byte[] keystore, EntityDescriptor descriptor) throws IOException {
    File zipFile = File.createTempFile("oiosaml-", ".zip");
    ZipOutputStream zos = new ZipOutputStream(new FileOutputStream(zipFile));
    zos.putNextEntry(new ZipEntry("oiosaml-sp.properties"));
    zos.write(renderTemplate("defaultproperties.vm", new HashMap<String, Object>() {
        {//from   w  w w .java  2 s .co  m
            put("homename", Constants.PROP_HOME);

            put("servletPath", contextPath);
            put("password", password);
        }
    }, false).getBytes());
    zos.closeEntry();

    zos.putNextEntry(new ZipEntry("metadata/SP/SPMetadata.xml"));
    zos.write(SAMLUtil.getSAMLObjectAsPrettyPrintXML(descriptor).getBytes());
    zos.closeEntry();

    zos.putNextEntry(new ZipEntry("metadata/IdP/IdPMetadata.xml"));
    zos.write(idpMetadata);
    zos.closeEntry();

    zos.putNextEntry(new ZipEntry("certificate/keystore"));
    zos.write(keystore);
    zos.closeEntry();

    zos.putNextEntry(new ZipEntry("oiosaml-sp.log4j.xml"));
    IOUtils.copy(getClass().getResourceAsStream("oiosaml-sp.log4j.xml"), zos);
    zos.closeEntry();

    zos.close();
    return zipFile;
}