Example usage for java.util.zip ZipOutputStream putNextEntry

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

Introduction

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

Prototype

public void putNextEntry(ZipEntry e) throws IOException 

Source Link

Document

Begins writing a new ZIP file entry and positions the stream to the start of the entry data.

Usage

From source file:azkaban.utils.Utils.java

private static void zipFile(String path, File input, ZipOutputStream zOut) throws IOException {
    if (input.isDirectory()) {
        File[] files = input.listFiles();
        if (files != null) {
            for (File f : files) {
                String childPath = path + input.getName() + (f.isDirectory() ? "/" : "");
                zipFile(childPath, f, zOut);
            }/*from w  w  w  .  ja  v a  2 s.  co m*/
        }
    } else {
        String childPath = path + (path.length() > 0 ? "/" : "") + input.getName();
        ZipEntry entry = new ZipEntry(childPath);
        zOut.putNextEntry(entry);
        InputStream fileInputStream = new BufferedInputStream(new FileInputStream(input));
        try {
            IOUtils.copy(fileInputStream, zOut);
        } finally {
            fileInputStream.close();
        }
    }
}

From source file:com.matze5800.paupdater.Functions.java

public static void addFilesToExistingZip(File zipFile, File[] files) throws IOException {
    File tempFile = new File(Environment.getExternalStorageDirectory() + "/pa_updater", "temp_kernel.zip");
    tempFile.delete();/*from  w  ww  .  j  a  v a2  s. c o  m*/

    boolean renameOk = zipFile.renameTo(tempFile);
    if (!renameOk) {
        throw new RuntimeException(
                "could not rename the file " + zipFile.getAbsolutePath() + " to " + tempFile.getAbsolutePath());
    }
    byte[] buf = new byte[1024];

    ZipInputStream zin = new ZipInputStream(new FileInputStream(tempFile));
    ZipOutputStream out = new ZipOutputStream(new FileOutputStream(zipFile));

    ZipEntry entry = zin.getNextEntry();
    while (entry != null) {
        String name = entry.getName();
        boolean notInFiles = true;
        for (File f : files) {
            if (f.getName().equals(name)) {
                notInFiles = false;
                break;
            }
        }
        if (notInFiles) {

            out.putNextEntry(new ZipEntry(name));

            int len;
            while ((len = zin.read(buf)) > 0) {
                out.write(buf, 0, len);
            }
        }
        entry = zin.getNextEntry();
    }
    zin.close();

    for (int i = 0; i < files.length; i++) {
        InputStream in = new FileInputStream(files[i]);
        out.putNextEntry(new ZipEntry(files[i].getName()));

        int len;
        while ((len = in.read(buf)) > 0) {
            out.write(buf, 0, len);
        }
        out.closeEntry();
        in.close();
    }
    out.close();
    tempFile.delete();
}

From source file:de.fu_berlin.inf.dpp.core.zip.FileZipper.java

private static void internalZipFiles(List<FileWrapper> files, File archive, boolean compress,
        boolean includeDirectories, long totalSize, ZipListener listener)
        throws IOException, OperationCanceledException {

    byte[] buffer = new byte[BUFFER_SIZE];

    OutputStream outputStream = new BufferedOutputStream(new FileOutputStream(archive), BUFFER_SIZE);

    ZipOutputStream zipStream = new ZipOutputStream(outputStream);

    zipStream.setLevel(compress ? Deflater.DEFAULT_COMPRESSION : Deflater.NO_COMPRESSION);

    boolean cleanup = true;
    boolean isCanceled = false;

    StopWatch stopWatch = new StopWatch();
    stopWatch.start();/* w  ww  .jav  a2s .c o  m*/

    long totalRead = 0L;

    try {
        for (FileWrapper file : files) {
            String entryName = includeDirectories ? file.getPath() : file.getName();

            if (listener != null) {
                isCanceled = listener.update(file.getPath());
            }

            log.trace("compressing file: " + entryName);

            zipStream.putNextEntry(new ZipEntry(entryName));

            InputStream in = null;

            try {
                int read = 0;
                in = file.getInputStream();
                while (-1 != (read = in.read(buffer))) {

                    if (isCanceled) {
                        throw new OperationCanceledException(
                                "compressing of file '" + entryName + "' was canceled");
                    }

                    zipStream.write(buffer, 0, read);

                    totalRead += read;

                    if (listener != null) {
                        listener.update(totalRead, totalSize);
                    }

                }
            } finally {
                IOUtils.closeQuietly(in);
            }
            zipStream.closeEntry();
        }
        cleanup = false;
    } finally {
        IOUtils.closeQuietly(zipStream);
        if (cleanup && archive != null && archive.exists() && !archive.delete()) {
            log.warn("could not delete archive file: " + archive);
        }
    }

    stopWatch.stop();

    log.debug(String.format("created archive %s I/O: [%s]", archive.getAbsolutePath(),
            CoreUtils.throughput(archive.length(), stopWatch.getTime())));

}

From source file:Main.java

private static void addFileToZip(String sourceFolderPath, String sourceFilePath, String baseFolderPath,
        ZipOutputStream zos) throws Exception {

    File item = new File(sourceFilePath);
    if (item == null || !item.exists())
        return; //skip if the file is not exist
    if (isSymLink(item))
        return; // do nothing to symbolic links.

    if (baseFolderPath == null)
        baseFolderPath = "";

    if (item.isDirectory()) {
        for (String subItem : item.list()) {
            addFileToZip(sourceFolderPath + File.separator + item.getName(),
                    sourceFilePath + File.separator + subItem, baseFolderPath, zos);
        }/*from   w w  w  . ja  va2 s  . c  o m*/
    } else {
        byte[] buf = new byte[102400]; //100k buffer
        int len;
        FileInputStream inStream = new FileInputStream(sourceFilePath);
        if (baseFolderPath.equals("")) //sourceFiles in absolute path, zip the file with absolute path
            zos.putNextEntry(new ZipEntry(sourceFilePath));
        else {//relative path
            String relativePath = sourceFilePath.substring(baseFolderPath.length());
            zos.putNextEntry(new ZipEntry(relativePath));
        }

        while ((len = inStream.read(buf)) > 0) {
            zos.write(buf, 0, len);
        }

    }
}

From source file:info.servertools.core.util.FileUtils.java

public static void zipDirectory(File directory, File zipfile, @Nullable Collection<String> fileBlacklist,
        @Nullable Collection<String> folderBlacklist) throws IOException {
    URI baseDir = directory.toURI();
    Deque<File> queue = new LinkedList<>();
    queue.push(directory);/*from   w  ww.j a  va 2  s . co m*/
    OutputStream out = new FileOutputStream(zipfile);
    Closeable res = out;
    try {
        ZipOutputStream zout = new ZipOutputStream(out);
        res = zout;
        while (!queue.isEmpty()) {
            directory = queue.removeFirst();
            File[] dirFiles = directory.listFiles();
            if (dirFiles != null && dirFiles.length != 0) {
                for (File child : dirFiles) {
                    if (child != null) {
                        String name = baseDir.relativize(child.toURI()).getPath();
                        if (child.isDirectory()
                                && (folderBlacklist == null || !folderBlacklist.contains(child.getName()))) {
                            queue.push(child);
                            name = name.endsWith("/") ? name : name + "/";
                            zout.putNextEntry(new ZipEntry(name));
                        } else {
                            if (fileBlacklist != null && !fileBlacklist.contains(child.getName())) {
                                zout.putNextEntry(new ZipEntry(name));
                                copy(child, zout);
                                zout.closeEntry();
                            }
                        }
                    }
                }
            }
        }
    } finally {
        res.close();
    }
}

From source file:net.semanticmetadata.lire.utils.FileUtils.java

public static void zipDirectory(File directory, File base, ZipOutputStream zos) throws IOException {
    File[] files = directory.listFiles();
    byte[] buffer = new byte[8192];
    int read = 0;
    for (int i = 0, n = files.length; i < n; i++) {
        if (files[i].isDirectory()) {
            zipDirectory(files[i], base, zos);
        } else {/*ww w. j  a  v a 2s. c o m*/
            FileInputStream in = new FileInputStream(files[i]);
            ZipEntry entry = new ZipEntry(files[i].getPath().substring(base.getPath().length() + 1));
            zos.putNextEntry(entry);
            while (-1 != (read = in.read(buffer))) {
                zos.write(buffer, 0, read);
            }
            in.close();
        }
    }
}

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

/**
 * This function zip the input file.//from w ww.  jav a2 s .c o m
 * 
 * @param file
 *            The input file to be zipped.
 * @param out
 *            The zip output stream.
 * @throws IOException
 */
public static void zipFile(final File file, final ZipOutputStream out) throws IOException {

    if (file != null && out != null) {

        // ///////////////////////////////////////////
        // Create a buffer for reading the files
        // ///////////////////////////////////////////

        byte[] buf = new byte[4096];

        FileInputStream in = null;

        try {
            in = new FileInputStream(file);

            // //////////////////////////////////
            // Add ZIP entry to output stream.
            // //////////////////////////////////

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

            // //////////////////////////////////////////////
            // 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();

        } 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.meltmedia.cadmium.core.util.WarUtils.java

/**
 * Adds a properties file to a war./*from  w  ww. java 2 s.  c o m*/
 * @param outZip The zip output stream to add to.
 * @param cadmiumPropertiesEntry The entry to add.
 * @param cadmiumProps The properties to store in the zip file.
 * @param newWarNames The first element of this list is used in a comment of the properties file.
 * @throws IOException
 */
public static void storeProperties(ZipOutputStream outZip, ZipEntry cadmiumPropertiesEntry,
        Properties cadmiumProps, List<String> newWarNames) throws IOException {
    ZipEntry newCadmiumEntry = new ZipEntry(cadmiumPropertiesEntry.getName());
    outZip.putNextEntry(newCadmiumEntry);
    cadmiumProps.store(outZip, "Initial git properties for " + newWarNames.get(0));
    outZip.closeEntry();
}

From source file:com.nuvolect.securesuite.util.OmniZip.java

public static boolean zipFiles(Context ctx, Iterable<OmniFile> files, OmniFile zipOmni, int destination) {

    ZipOutputStream zos = null;
    LogUtil.log(LogUtil.LogType.OMNI_ZIP, "ZIPPING TO: " + zipOmni.getPath());

    try {//from w  w w  . j av  a 2s . c om
        zos = new ZipOutputStream(zipOmni.getOutputStream());

        for (OmniFile file : files) {

            if (file.isDirectory()) {

                zipSubDirectory(ctx, "", file, zos);
            } else {

                LogUtil.log(LogUtil.LogType.OMNI_ZIP,
                        "zipping up: " + file.getPath() + " (bytes: " + file.length() + ")");

                /**
                 * Might get lucky here, can it associate the name with the copyLarge that follows
                 */
                ZipEntry ze = new ZipEntry(file.getName());
                zos.putNextEntry(ze);

                IOUtils.copyLarge(file.getFileInputStream(), zos);

                zos.flush();
            }
        }

        zos.close();
        return true;
    } catch (IOException e) {
        LogUtil.logException(LogUtil.LogType.OMNI_ZIP, e);
        e.printStackTrace();
    }

    return false;
}

From source file:game.com.HandleDownloadFolderServlet.java

public static void addDirToZipArchive(ZipOutputStream zos, File fileToZip, String parrentDirectoryName)
        throws Exception {
    if (fileToZip == null || !fileToZip.exists()) {
        return;//from   w w  w  .ja  va  2  s.  c  o  m
    }

    String zipEntryName = fileToZip.getName();
    if (parrentDirectoryName != null && !parrentDirectoryName.isEmpty()) {
        zipEntryName = parrentDirectoryName + "/" + fileToZip.getName();
    }

    if (fileToZip.isDirectory()) {
        System.out.println("+" + zipEntryName);
        for (File file : fileToZip.listFiles()) {
            addDirToZipArchive(zos, file, zipEntryName);
        }
    } else {
        System.out.println("   " + zipEntryName);
        byte[] buffer = new byte[1024];
        FileInputStream fis = new FileInputStream(fileToZip);
        zos.putNextEntry(new ZipEntry(zipEntryName));
        int length;
        while ((length = fis.read(buffer)) > 0) {
            zos.write(buffer, 0, length);
        }
        zos.closeEntry();
        fis.close();
    }
}