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.utils.ZipUtils.java

/**
 * zip//w ww .  ja  v a  2 s  . c  o  m
 *
 * @param zipFile
 * @param file
 * @param destPath  ?
 * @param overwrite ?
 * @throws IOException
 */
public static void addFileToZipFile(File zipFile, File outZipFile, File file, String destPath,
        boolean overwrite) throws IOException {
    byte[] buf = new byte[1024];
    ZipInputStream zin = new ZipInputStream(new FileInputStream(zipFile));
    ZipOutputStream out = new ZipOutputStream(new FileOutputStream(outZipFile));
    ZipEntry entry = zin.getNextEntry();
    boolean addFile = true;
    while (entry != null) {
        boolean addEntry = true;
        String name = entry.getName();
        if (StringUtils.equalsIgnoreCase(name, destPath)) {
            if (overwrite) {
                addEntry = false;
            } else {
                addFile = false;
            }
        }
        if (addEntry) {
            ZipEntry zipEntry = null;
            if (ZipEntry.STORED == entry.getMethod()) {
                zipEntry = new ZipEntry(entry);
            } else {
                zipEntry = new ZipEntry(name);
            }
            out.putNextEntry(zipEntry);
            int len;
            while ((len = zin.read(buf)) > 0) {
                out.write(buf, 0, len);
            }
        }
        entry = zin.getNextEntry();
    }

    if (addFile) {
        InputStream in = new FileInputStream(file);
        // Add ZIP entry to output stream.
        ZipEntry zipEntry = new ZipEntry(destPath);
        out.putNextEntry(zipEntry);
        // 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();
    }
    // Close the streams
    zin.close();
    out.close();
}

From source file:moskitt4me.repositoryClient.core.util.RepositoryClientUtil.java

public static void addFolderToZip(File folder, String parentFolder, ZipOutputStream zos) throws Exception {

    for (File file : folder.listFiles()) {

        if (file.isDirectory()) {
            zos.putNextEntry(new ZipEntry(parentFolder + file.getName() + "/"));
            zos.closeEntry();// w  w w. j  av a2  s  . c om
            addFolderToZip(file, parentFolder + file.getName() + "/", zos);
            continue;
        } else {
            zos.putNextEntry(new ZipEntry(parentFolder + file.getName()));
            BufferedInputStream bis = new BufferedInputStream(new FileInputStream(file));

            long bytesRead = 0;
            byte[] bytesIn = new byte[1024];
            int read = 0;

            while ((read = bis.read(bytesIn)) != -1) {
                zos.write(bytesIn, 0, read);
                bytesRead += read;
            }

            zos.closeEntry();
            bis.close();
        }
    }
}

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.ja  v  a  2 s  .  co 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:it.geosolutions.tools.compress.file.Compressor.java

/**
 * @param outputDir//from   www  .  j a  v a2 s . c  o  m
 *            The directory where the zipfile will be created
 * @param zipFileBaseName
 *            The basename of hte zip file (i.e.: a .zip will be appended)
 * @param folder
 *            The folder that will be compressed
 * @return The created zipfile, or null if an error occurred.
 * @deprecated TODO UNTESTED
 */
public static File deflate(final File outputDir, final String zipFileBaseName, final File folder) {
    // Create a buffer for reading the files
    byte[] buf = new byte[4096];

    // Create the ZIP file
    final File outZipFile = new File(outputDir, zipFileBaseName + ".zip");
    if (outZipFile.exists()) {
        if (LOGGER.isInfoEnabled())
            LOGGER.info("The output file already exists: " + outZipFile);
        return outZipFile;
    }
    ZipOutputStream out = null;
    BufferedOutputStream bos = null;
    FileOutputStream fos = null;
    try {
        fos = new FileOutputStream(outZipFile);
        bos = new BufferedOutputStream(fos);
        out = new ZipOutputStream(bos);
        Collector c = new Collector(null);
        List<File> files = c.collect(folder);
        // Compress the files
        for (File file : files) {
            FileInputStream in = null;
            try {
                in = new FileInputStream(file);
                if (file.isDirectory()) {
                    out.putNextEntry(new ZipEntry(Path.toRelativeFile(folder, file).getPath()));
                } else {
                    // Add ZIP entry to output stream.
                    out.putNextEntry(new ZipEntry(FilenameUtils.getBaseName(file.getName())));
                    // Transfer bytes from the file to the ZIP file
                    int len;
                    while ((len = in.read(buf)) > 0) {
                        out.write(buf, 0, len);
                    }
                }

            } finally {
                try {
                    // Complete the entry
                    out.closeEntry();
                } catch (IOException e) {
                }
                IOUtils.closeQuietly(in);
            }

        }

    } catch (IOException e) {
        LOGGER.error(e.getLocalizedMessage(), e);
        return null;
    } finally {

        // Complete the ZIP file
        IOUtils.closeQuietly(bos);
        IOUtils.closeQuietly(fos);
        IOUtils.closeQuietly(out);
    }

    return outZipFile;
}

From source file:Main.java

/**
 * zips a directory//from  w w w.ja  v  a  2 s .co  m
 * @param dir2zip
 * @param zipOut
 * @param zipFileName
 * @throws IOException
 */
private static void zipDir(String dir2zip, ZipOutputStream zipOut, String zipFileName) throws IOException {
    File zipDir = new File(dir2zip);
    // get a listing of the directory content
    String[] dirList = zipDir.list();
    byte[] readBuffer = new byte[2156];
    int bytesIn = 0;
    // loop through dirList, and zip the files
    for (int i = 0; i < dirList.length; i++) {
        File f = new File(zipDir, dirList[i]);
        if (f.isDirectory()) {
            // if the File object is a directory, call this
            // function again to add its content recursively
            String filePath = f.getPath();
            zipDir(filePath, zipOut, zipFileName);
            // loop again
            continue;
        }

        if (f.getName().equals(zipFileName)) {
            continue;
        }
        // if we reached here, the File object f was not a directory
        // create a FileInputStream on top of f
        final InputStream fis = new BufferedInputStream(new FileInputStream(f));
        try {
            ZipEntry anEntry = new ZipEntry(f.getPath().substring(dir2zip.length() + 1));
            // place the zip entry in the ZipOutputStream object
            zipOut.putNextEntry(anEntry);
            // now write the content of the file to the ZipOutputStream
            while ((bytesIn = fis.read(readBuffer)) != -1) {
                zipOut.write(readBuffer, 0, bytesIn);
            }
        } finally {
            // close the Stream
            fis.close();
        }
    }
}

From source file:com.wabacus.WabacusFacade.java

private static void tarFileToZip(String originFilePath, String zipFilePath) {
    if (Tools.isEmpty(originFilePath) || Tools.isEmpty(zipFilePath))
        return;//w w  w.ja  v  a 2 s  . c om
    int idx = originFilePath.lastIndexOf(File.separator);
    String fileName = idx > 0 ? originFilePath.substring(idx + File.separator.length()) : originFilePath;//???
    idx = fileName.lastIndexOf("_");
    if (idx > 0)
        fileName = fileName.substring(idx + 1).trim();
    try {
        FileOutputStream fout = new FileOutputStream(zipFilePath);
        ZipOutputStream zipout = new ZipOutputStream(fout);
        FileInputStream fis = new FileInputStream(originFilePath);
        zipout.putNextEntry(new ZipEntry(fileName));
        byte[] buffer = new byte[1024];
        int len;
        while ((len = fis.read(buffer)) != -1) {
            zipout.write(buffer, 0, len);
        }
        zipout.closeEntry();
        fis.close();
        zipout.close();
        fout.close();
    } catch (Exception e) {
        throw new WabacusRuntimeException("" + originFilePath + "zip", e);
    }
}

From source file:de.uzk.hki.da.pkg.ZipArchiveBuilder.java

private void addFileToArchive(String path, File srcFile, ZipOutputStream zip, boolean includeFolder)
        throws Exception {

    if (srcFile.isDirectory()) {
        addFolderToArchive(path, srcFile, zip, includeFolder);
    } else {//from   ww w.  ja  va2  s  .com
        byte[] buf = new byte[1024];
        int len;
        FileInputStream in = new FileInputStream(srcFile);
        zip.putNextEntry(new ZipEntry(path + "/" + srcFile.getName()));
        while ((len = in.read(buf)) > 0) {
            zip.write(buf, 0, len);
        }
        in.close();
    }

    zip.flush();

}

From source file:org.carlspring.strongbox.artifact.generator.NugetPackageGenerator.java

private void createRandomNupkgFile(ZipOutputStream zos) throws IOException {
    ZipEntry ze = new ZipEntry("lib/random-size-file");
    zos.putNextEntry(ze);//from w w w  . j a  v  a2 s .  c  om

    RandomInputStream ris = new RandomInputStream(true, 1000000);

    byte[] buffer = new byte[4096];
    int len;
    while ((len = ris.read(buffer)) > 0) {
        zos.write(buffer, 0, len);
    }

    ris.close();
    zos.closeEntry();
}

From source file:com.yunmel.syncretic.utils.io.IOUtils.java

private static void compressFile(File file, String fileName, ZipOutputStream zipout, String baseDir) {
    try {//from  ww w.  ja va  2s. c  o m
        ZipEntry entry = null;
        if (baseDir.equals("/")) {
            baseDir = "";
        }
        String filename = new String((baseDir + fileName).getBytes(), "GBK");
        entry = new ZipEntry(filename);

        entry.setSize(file.length());
        zipout.putNextEntry(entry);
        BufferedInputStream fr = new BufferedInputStream(new FileInputStream(file));
        int len;
        byte[] buffer = new byte[1024];
        while ((len = fr.read(buffer)) != -1)
            zipout.write(buffer, 0, len);
        fr.close();
    } catch (IOException e) {
    }
}

From source file:gdt.data.entity.ArchiveHandler.java

private static void appendToZip(String directoryToZip$, File file, ZipOutputStream zos) {
    try {/*w  w w  .  j  av a2  s.com*/
        FileInputStream fis = new FileInputStream(file);
        String zipFile$ = file.getPath().substring(directoryToZip$.length() + 1, file.getPath().length());
        //System.out.println("Writing '" + zipFile$ + "' to zip file");
        ZipEntry zipEntry = new ZipEntry(zipFile$);
        zos.putNextEntry(zipEntry);
        byte[] bytes = new byte[1024];
        int length;
        while ((length = fis.read(bytes)) >= 0) {
            zos.write(bytes, 0, length);
        }
        zos.closeEntry();
        fis.close();
    } catch (Exception e) {
        Logger.getLogger(ArchiveHandler.class.getName()).severe(e.toString());
    }
}