Example usage for java.util.zip ZipOutputStream write

List of usage examples for java.util.zip ZipOutputStream write

Introduction

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

Prototype

public synchronized void write(byte[] b, int off, int len) throws IOException 

Source Link

Document

Writes an array of bytes to the current ZIP entry data.

Usage

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

public static void splitZip(File inputFile, File outputFile, Set<String> includeEnties) throws IOException {
    if (outputFile.exists()) {
        FileUtils.deleteQuietly(outputFile);
    }/*from ww  w  . ja v  a2  s  .c o  m*/
    if (null == includeEnties || includeEnties.size() < 1) {
        return;
    }
    FileOutputStream fos = new FileOutputStream(outputFile);
    ZipOutputStream jos = new ZipOutputStream(fos);
    final byte[] buffer = new byte[8192];
    FileInputStream fis = new FileInputStream(inputFile);
    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()) {
                continue;
            }
            String name = entry.getName();
            if (!includeEnties.contains(name)) {
                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();
}

From source file:nl.edia.sakai.tool.skinmanager.impl.SkinFileSystemServiceImpl.java

private void writeZipEntry(String prefix, ZipOutputStream out, File file)
        throws IOException, FileNotFoundException {
    ZipEntry mySkinFile = new ZipEntry(prefix + file.getName());
    mySkinFile.setSize(file.length());/*from w w  w.  jav  a2s  . co m*/
    mySkinFile.setTime(file.lastModified());
    out.putNextEntry(mySkinFile);

    byte[] buf = new byte[1024];
    InputStream in = new FileInputStream(file);
    try {
        // Transfer bytes from the file to the ZIP file
        int len;
        while ((len = in.read(buf)) > 0) {
            out.write(buf, 0, len);
        }
    } finally {
        in.close();
    }
    // Complete the entry
    out.closeEntry();
}

From source file:com.clustercontrol.collect.util.ZipCompresser.java

/**
 * ?????1????// ww w.  ja  v  a 2s . co m
 * 
 * @param inputFileNameList ??
 * @param outputFileName ?
 * 
 * @return ???
 */
protected static synchronized void archive(ArrayList<String> inputFileNameList, String outputFileName)
        throws HinemosUnknown {
    m_log.debug("archive() output file = " + outputFileName);

    byte[] buf = new byte[128];
    BufferedInputStream in = null;
    ZipEntry entry = null;
    ZipOutputStream out = null;

    // ?
    if (outputFileName == null || "".equals(outputFileName)) {
        HinemosUnknown e = new HinemosUnknown("archive output fileName is null ");
        m_log.info("archive() : " + e.getClass().getSimpleName() + ", " + e.getMessage());
        throw e;
    }
    File zipFile = new File(outputFileName);
    if (zipFile.exists()) {
        if (zipFile.isFile() && zipFile.canWrite()) {
            m_log.debug("archive() output file = " + outputFileName
                    + " is exists & file & writable. initialize file(delete)");
            if (!zipFile.delete())
                m_log.debug("Fail to delete " + zipFile.getAbsolutePath());
        } else {
            HinemosUnknown e = new HinemosUnknown("archive output fileName is directory or not writable ");
            m_log.info("archive() : " + e.getClass().getSimpleName() + ", " + e.getMessage());
            throw e;
        }
    }

    // ?
    try {
        // ????
        out = new ZipOutputStream(new FileOutputStream(outputFileName));

        for (String inputFileName : inputFileNameList) {
            m_log.debug("archive() input file name = " + inputFileName);

            // ????
            in = new BufferedInputStream(new FileInputStream(inputFileName));

            // ??
            String fileName = (new File(inputFileName)).getName();
            m_log.debug("archive() entry file name = " + fileName);
            entry = new ZipEntry(fileName);

            out.putNextEntry(entry);
            // ????
            int size;
            while ((size = in.read(buf, 0, buf.length)) != -1) {
                out.write(buf, 0, size);
            }
            // ??
            out.closeEntry();
            in.close();
        }
        // ? out.flush();
        out.close();

    } catch (IOException e) {
        m_log.warn("archive() archive error : " + outputFileName + e.getClass().getSimpleName() + ", "
                + e.getMessage(), e);
        throw new HinemosUnknown("archive error " + outputFileName, e);

    } finally {

        if (in != null) {
            try {
                in.close();
            } catch (IOException e) {
            }
        }

        if (out != null) {
            try {
                out.close();
            } catch (IOException e) {
            }
        }
    }
}

From source file:link.kjr.file_manager.MainActivity.java

public void createZipFile(String name, final MainActivity activity) {

    activity.handler.post(new Runnable() {
        @Override//  w w  w . j a  v  a2s  . c o m
        public void run() {
            activity.postMessage(activity.getBaseContext().getString(R.string.creating_zip_file));
        }
    });

    try {
        ZipOutputStream zos = new ZipOutputStream(new FileOutputStream(currentPath + "/" + name + ".zip"));
        for (String file : selectedFiles) {

            ZipEntry ze = new ZipEntry(file);
            FileInputStream fis = new FileInputStream(file);

            zos.putNextEntry(ze);
            byte[] data = new byte[1024];
            int length;
            while ((length = fis.read(data)) >= 0) {
                zos.write(data, 0, length);
            }
            zos.closeEntry();
            fis.close();
        }
        zos.close();
    } catch (FileNotFoundException fnfe) {
        fnfe.printStackTrace();
    } catch (IOException ioe) {
        ioe.printStackTrace();
    }
    activity.handler.post(new Runnable() {
        @Override
        public void run() {
            activity.postMessage(activity.getBaseContext().getString(R.string.done_creating_zip_file));
            activity.deselectFiles();
            activity.refresh();
        }
    });

}

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

/**
 * API to zip list of files to a desired file. Operation aborted if any file is invalid or a directory.
 * /*from   www.  ja va 2  s  .com*/
 * @param filePaths {@link List}< {@link String}>
 * @param outputFilePath {@link String}
 * @throws IOException in case of error
 */
public static void zipMultipleFiles(List<String> filePaths, String outputFilePath) throws IOException {
    LOGGER.info("Zipping files to " + outputFilePath + ".zip file");
    File outputFile = new File(outputFilePath);

    if (outputFile.exists()) {
        LOGGER.info(outputFilePath + " file already exists. Deleting existing and creating a new file.");
        outputFile.delete();
    }

    byte[] buffer = new byte[UtilConstants.BUFFER_CONST]; // Create a buffer for copying
    int bytesRead;
    ZipOutputStream out = null;
    FileInputStream input = null;
    try {
        out = new ZipOutputStream(new FileOutputStream(outputFilePath));
        for (String filePath : filePaths) {
            LOGGER.info("Writing file " + filePath + " into zip file.");

            File file = new File(filePath);
            if (!file.exists() || file.isDirectory()) {
                throw new Exception("Invalid file: " + file.getAbsolutePath()
                        + ". Either file does not exists or it is a directory.");
            }
            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);
            }

        }

    } catch (Exception e) {
        LOGGER.error("Exception occured while zipping file." + e.getMessage(), e);
    } finally {
        if (input != null) {
            input.close();
        }
        if (out != null) {
            out.close();
        }
    }
}

From source file:com.microsoft.tfs.client.common.ui.teambuild.commands.CreateUploadZipCommand.java

/**
 * Copy zip file and remove ignored files
 *
 * @param srcFile// w  ww.  j a v a2  s  .c o  m
 * @param destFile
 * @throws IOException
 */
public void copyZip(final String srcFile, final String destFile) throws Exception {
    loadDefaultExcludePattern(getRootFolderInZip(srcFile));

    final ZipFile zipSrc = new ZipFile(srcFile);
    final ZipOutputStream out = new ZipOutputStream(new FileOutputStream(destFile));

    try {
        final Enumeration<? extends ZipEntry> entries = zipSrc.entries();
        while (entries.hasMoreElements()) {
            final ZipEntry entry = entries.nextElement();
            if (!isExcluded(LocalPath.combine(srcFile, entry.getName()), false, srcFile)) {
                final ZipEntry newEntry = new ZipEntry(entry.getName());
                out.putNextEntry(newEntry);

                final BufferedInputStream in = new BufferedInputStream(zipSrc.getInputStream(entry));
                int len;
                final byte[] buf = new byte[65536];
                while ((len = in.read(buf)) > 0) {
                    out.write(buf, 0, len);
                }
                out.closeEntry();
                in.close();
            }
        }
        out.finish();
    } catch (final IOException e) {
        errorMsg = Messages.getString("CreateUploadZipCommand.CopyArchiveErrorMessageFormat"); //$NON-NLS-1$
        log.error("Exceptions when copying exising archive ", e); //$NON-NLS-1$
        throw e;
    } finally {
        out.close();
        zipSrc.close();
    }
}

From source file:com.veniosg.dir.mvvm.model.storage.operation.CompressOperation.java

/**
 * Recursively compress a File./*from ww w.jav a 2  s. co  m*/
 *
 * @return How many files where compressed.
 */
private int compressCore(int notId, ZipOutputStream zipStream, File toCompress, String internalPath,
        int filesCompressed, final int fileCount, File zipFile) throws IOException {
    if (internalPath == null)
        internalPath = "";

    showCompressProgressNotification(filesCompressed, fileCount, notId, zipFile, toCompress, context);
    if (toCompress.isFile()) {
        byte[] buf = new byte[BUFFER_SIZE];
        int len;
        FileInputStream in = new FileInputStream(toCompress);

        // Create internal zip file entry.
        ZipEntry entry;
        if (internalPath.length() > 0) {
            entry = new ZipEntry(internalPath + "/" + toCompress.getName());
        } else {
            entry = new ZipEntry(toCompress.getName());
        }
        entry.setTime(toCompress.lastModified());
        zipStream.putNextEntry(entry);

        // Compress
        while ((len = in.read(buf)) > 0) {
            zipStream.write(buf, 0, len);
        }

        filesCompressed++;
        zipStream.closeEntry();
        in.close();
    } else {
        if (toCompress.list().length == 0) {
            zipStream.putNextEntry(new ZipEntry(internalPath + "/" + toCompress.getName() + "/"));
            zipStream.closeEntry();
        } else {
            for (File child : toCompress.listFiles()) {
                filesCompressed = compressCore(notId, zipStream, child,
                        internalPath + "/" + toCompress.getName(), filesCompressed, fileCount, zipFile);
            }
        }
    }

    return filesCompressed;
}

From source file:fr.fastconnect.factory.tibco.bw.fcunit.PrepareTestMojo.java

private void removeFileInZipContaining(List<String> contentFilter, File zipFile)
        throws ZipException, IOException {
    ZipScanner zs = new ZipScanner();
    zs.setSrc(zipFile);//from  w ww  .  java2 s  . c o m
    String[] includes = { "**/*.process" };
    zs.setIncludes(includes);
    //zs.setCaseSensitive(true);
    zs.init();
    zs.scan();

    File originalProjlib = zipFile; // to be overwritten
    File tmpProjlib = new File(zipFile.getAbsolutePath() + ".tmp"); // to read
    FileUtils.copyFile(originalProjlib, tmpProjlib);

    ZipFile listZipFile = new ZipFile(tmpProjlib);
    ZipInputStream readZipFile = new ZipInputStream(new FileInputStream(tmpProjlib));
    ZipOutputStream writeZipFile = new ZipOutputStream(new FileOutputStream(originalProjlib));

    ZipEntry zipEntry;
    boolean keep;
    while ((zipEntry = readZipFile.getNextEntry()) != null) {
        keep = true;
        for (String filter : contentFilter) {
            keep = keep && !containsString(filter, listZipFile.getInputStream(zipEntry));
        }
        //         if (!containsString("<pd:type>com.tibco.pe.core.OnStartupEventSource</pd:type>", listZipFile.getInputStream(zipEntry))
        //          && !containsString("<pd:type>com.tibco.plugin.jms.JMSTopicEventSource</pd:type>", listZipFile.getInputStream(zipEntry))) {
        if (keep) {
            writeZipFile.putNextEntry(zipEntry);
            int len = 0;
            byte[] buf = new byte[1024];
            while ((len = readZipFile.read(buf)) >= 0) {
                writeZipFile.write(buf, 0, len);
            }
            writeZipFile.closeEntry();
            //getLog().info("written");
        } else {
            getLog().info("removed " + zipEntry.getName());
        }

    }

    writeZipFile.close();
    readZipFile.close();
    listZipFile.close();

    originalProjlib.setLastModified(originalProjlib.lastModified() - 100000);
}

From source file:edu.kit.dama.util.ZipUtils.java

/**
 * Write a list of files into a ZipOutputStream. The provided base path is
 * used to keep the structure defined by pFileList within the zip file.<BR/>
 * Due to the fact, that we have only one single base path, all files within
 * 'pFileList' must have in the same base directory. Adding files from a
 * higher level will cause unexpected zip entries.
 *
 * @param pFileList The list of input files
 * @param pBasePath The base path the will be removed from all file paths
 * before creating a new zip entry/*from w ww .  j a v a2  s.  c  om*/
 * @param pZipOut The zip output stream
 * @throws IOException If something goes wrong, in most cases if there are
 * problems with reading the input files or writing into the output file
 */
private static void zip(File[] pFileList, String pBasePath, ZipOutputStream pZipOut) throws IOException {
    // Create a buffer for reading the files
    byte[] buf = new byte[1024];
    try {
        // Compress the files
        LOGGER.debug("Adding {} files to archive", pFileList.length);

        for (File pFileList1 : pFileList) {
            String entryName = pFileList1.getPath().replaceAll(Pattern.quote(pBasePath), "");
            if (entryName.startsWith(File.separator)) {
                entryName = entryName.substring(1);
            }

            if (pFileList1.isDirectory()) {
                LOGGER.debug("Adding directory entry");
                //add empty folders, too
                pZipOut.putNextEntry(new ZipEntry((entryName + File.separator).replaceAll("\\\\", "/")));
                pZipOut.closeEntry();
                File[] fileList = pFileList1.listFiles();
                if (fileList.length != 0) {
                    LOGGER.debug("Adding directory content recursively");
                    zip(fileList, pBasePath, pZipOut);
                } else {
                    LOGGER.debug("Skipping recursive call due to empty directory");
                }
                //should we close the entry here??
                //pZipOut.closeEntry();
            } else {
                LOGGER.debug("Adding file entry");
                try (final FileInputStream in = new FileInputStream(pFileList1)) {
                    // Add ZIP entry to output stream.
                    pZipOut.putNextEntry(new ZipEntry(entryName.replaceAll("\\\\", "/")));
                    // Transfer bytes from the file to the ZIP file
                    int len;
                    while ((len = in.read(buf)) > 0) {
                        pZipOut.write(buf, 0, len);
                    }
                    // Complete the entry
                    LOGGER.debug("Closing file entry");
                    pZipOut.closeEntry();
                }
            }
        }
    } catch (IOException ioe) {
        LOGGER.error(
                "Aborting zip process due to an IOException caused by any zip stream (FileInput or ZipOutput)",
                ioe);
        throw ioe;
    } catch (RuntimeException e) {
        LOGGER.error("Aborting zip process due to an unexpected exception", e);
        throw new IOException("Unexpected exception during zip operation", e);
    }
}

From source file:com.taobao.android.builder.tools.zip.ZipUtils.java

public static void rezip(File output, File srcDir, Map<String, ZipEntry> zipEntryMethodMap) throws Exception {
    if (output.isDirectory()) {
        throw new IOException("This is a directory!");
    }/*from   w  ww  .  j  a  v  a  2s  . c  o m*/
    if (!output.getParentFile().exists()) {
        output.getParentFile().mkdirs();
    }

    if (!output.exists()) {
        output.createNewFile();
    }
    List fileList = getSubFiles(srcDir);
    ZipOutputStream zos = new ZipOutputStream(new FileOutputStream(output));
    ZipEntry ze = null;
    byte[] buf = new byte[1024];
    int readLen = 0;
    for (int i = 0; i < fileList.size(); i++) {
        File f = (File) fileList.get(i);
        ze = new ZipEntry(getAbsFileName(srcDir.getPath(), f));
        ze.setSize(f.length());
        ze.setTime(f.lastModified());
        if (zipEntryMethodMap != null) {
            ZipEntry originEntry = zipEntryMethodMap.get(ze.getName());
            if (originEntry != null) {
                if (originEntry.getMethod() == STORED) {
                    ze.setCompressedSize(f.length());
                    InputStream in = new BufferedInputStream(new FileInputStream(f));
                    try {
                        CRC32 crc = new CRC32();
                        int c;
                        while ((c = in.read()) != -1) {
                            crc.update(c);
                        }
                        ze.setCrc(crc.getValue());
                    } finally {
                        in.close();
                    }
                }
                ze.setMethod(originEntry.getMethod());
            }
        }
        zos.putNextEntry(ze);
        InputStream is = new BufferedInputStream(new FileInputStream(f));
        while ((readLen = is.read(buf, 0, 1024)) != -1) {
            zos.write(buf, 0, readLen);
        }
        is.close();
    }
    zos.close();
}