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:de.thischwa.pmcms.tool.compression.Zip.java

/**
 * Static method to compress all files based on the ImputStream in 'entries' into 'zip'. 
 * Each entry has a InputStream and its String representation in the zip.
 * //from  w w  w .  ja v a 2s. co  m
 * @param zip The zip file. It will be deleted if exists. 
 * @param entries Map<File, String>
 * @param monitor Must be initialized correctly by the caller.
 * @throws IOException
 */
public static void compress(final File zip, final Map<InputStream, String> entries,
        final IProgressMonitor monitor) throws IOException {
    if (zip == null || entries == null || CollectionUtils.isEmpty(entries.keySet()))
        throw new IllegalArgumentException("One ore more parameters are empty!");
    if (zip.exists())
        zip.delete();
    else if (!zip.getParentFile().exists())
        zip.getParentFile().mkdirs();

    ZipOutputStream out = new ZipOutputStream(new BufferedOutputStream(new FileOutputStream(zip)));
    out.setLevel(Deflater.BEST_COMPRESSION);
    try {
        for (InputStream inputStream : entries.keySet()) {
            // skip beginning slash, because can cause errors in other zip apps
            ZipEntry zipEntry = new ZipEntry(skipBeginningSlash(entries.get(inputStream)));
            out.putNextEntry(zipEntry);
            IOUtils.copy(inputStream, out);
            out.closeEntry();
            inputStream.close();
            if (monitor != null)
                monitor.worked(1);
        }
    } finally { // cleanup
        IOUtils.closeQuietly(out);
    }
}

From source file:gov.va.chir.tagline.dao.FileDao.java

private static void saveZipFile(final File zipFile, final File... inputFiles) throws IOException {
    byte[] buffer = new byte[BUFFER_SIZE];

    final ZipOutputStream zos = new ZipOutputStream(new FileOutputStream(zipFile));

    for (File file : inputFiles) {
        final ZipEntry entry = new ZipEntry(file.getName());
        zos.putNextEntry(entry);

        final FileInputStream in = new FileInputStream(file);
        int len;//from   ww w .j a v  a2  s .c o  m
        while ((len = in.read(buffer)) > 0) {
            zos.write(buffer, 0, len);
        }

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

    zos.close();
}

From source file:com.dreikraft.axbo.sound.SoundPackageUtil.java

private static void writeZipEntry(final String entryName, final ZipOutputStream out, final InputStream in)
        throws IOException {
    try {/*from   w  ww  .j a  v a 2 s . com*/
        ZipEntry fileEntry = new ZipEntry(entryName);
        out.putNextEntry(fileEntry);
        final byte[] buf = new byte[BUF_SIZE];
        int avail;
        while ((avail = in.read(buf)) != -1) {
            out.write(buf, 0, avail);
        }
    } finally {
        out.flush();
        out.closeEntry();
    }
}

From source file:au.org.ands.vocabs.toolkit.utils.ToolkitFileUtils.java

/** Add a file to a ZIP archive.
 * @param zos The ZipOutputStream representing the ZIP archive.
 * @param file The File which is to be added to the ZIP archive.
 * @return True if adding succeeded.//w  w w .java 2  s  . co  m
 * @throws IOException Any exception when reading/writing data.
 */
private static boolean zipFile(final ZipOutputStream zos, final File file) throws IOException {
    if (!file.canRead()) {
        logger.error("zipFile can not read " + file.getCanonicalPath());
        return false;
    }
    zos.putNextEntry(new ZipEntry(file.getName()));
    FileInputStream fis = new FileInputStream(file);

    byte[] buffer = new byte[BUFFER_SIZE];
    int byteCount = 0;
    while ((byteCount = fis.read(buffer)) != -1) {
        zos.write(buffer, 0, byteCount);
    }
    fis.close();
    zos.closeEntry();
    return true;
}

From source file:net.sourceforge.dita4publishers.word2dita.Word2DitaValidationHelper.java

/**
 * @param documentDom//www . ja v a 2 s .  c o  m
 * @param commentsDom
 * @param docxZip
 * @param zipFile
 * @throws FileNotFoundException
 * @throws IOException
 * @throws Exception
 */
public static void saveZipComponents(ZipComponents zipComponents, File zipFile)
        throws FileNotFoundException, IOException, Exception {
    ZipOutputStream zipOutStream = new ZipOutputStream(new FileOutputStream(zipFile));
    for (ZipComponent comp : zipComponents.getComponents()) {
        ZipEntry newEntry = new ZipEntry(comp.getName());
        zipOutStream.putNextEntry(newEntry);
        if (comp.isDirectory()) {
            // Nothing to do.
        } else {
            // System.out.println(" + [DEBUG] saving component \"" + comp.getName() + "\"");
            if (comp.getName().endsWith("document.xml") || comp.getName().endsWith("document.xml.rels")) {
                // System.out.println("Handling a file of interest.");
            }
            InputStream inputStream = comp.getInputStream();
            IOUtils.copy(inputStream, zipOutStream);
            inputStream.close();
        }
    }
    zipOutStream.close();
}

From source file:net.grinder.util.LogCompressUtil.java

/**
 * Compress multiple Files.//from   ww  w.jav  a2s  . com
 * 
 * @param logFiles
 *            files to be compressed
 * @return compressed file byte array
 */
public static byte[] compressFile(File[] logFiles) {
    FileInputStream fio = null;
    ByteArrayOutputStream out = null;
    ZipOutputStream zos = null;
    try {

        out = new ByteArrayOutputStream();
        zos = new ZipOutputStream(out);
        for (File each : logFiles) {
            try {
                fio = new FileInputStream(each);
                ZipEntry zipEntry = new ZipEntry(each.getName());
                zipEntry.setTime(each.lastModified());
                zos.putNextEntry(zipEntry);
                byte[] buffer = new byte[COMPRESS_BUFFER_SIZE];
                int count = 0;
                while ((count = fio.read(buffer, 0, COMPRESS_BUFFER_SIZE)) != -1) {
                    zos.write(buffer, 0, count);
                }
                zos.closeEntry();
            } catch (IOException e) {
                LOGGER.error("Error occurs while compress {}", each.getAbsolutePath());
                LOGGER.error("Details", e);
            } finally {
                IOUtils.closeQuietly(fio);
            }
        }
        zos.finish();
        zos.flush();
        return out.toByteArray();
    } catch (IOException e) {
        LOGGER.info("Error occurs while compress log : {} ", e.getMessage());
        LOGGER.debug("Details", e);
        return null;
    } finally {
        IOUtils.closeQuietly(zos);
        IOUtils.closeQuietly(fio);
        IOUtils.closeQuietly(out);
    }
}

From source file:com.ecofactor.qa.automation.platform.util.FileUtil.java

/**
 * Adds the file to zip.//from  w  ww  . j av  a2s. c om
 * @param path the path
 * @param srcFile the src file
 * @param zip the zip
 */
private static void addFileToZip(final String path, final String srcFile, final ZipOutputStream zip) {

    try {
        final File folder = new File(srcFile);
        if (folder.isDirectory()) {
            addFolderToZip(path, srcFile, zip);
        } else {
            final byte[] buf = new byte[1024];
            int len;
            final FileInputStream inputStream = new FileInputStream(srcFile);
            zip.putNextEntry(
                    new ZipEntry(new StringBuilder(path).append(SLASH).append(folder.getName()).toString()));
            do {
                len = inputStream.read(buf);
                zip.write(buf, 0, len);
            } while (len > 0);
            inputStream.close();
        }
    } catch (IOException e) {
        LOGGER.error("Error in add flies to zip", e);
    }
}

From source file:net.firejack.platform.core.utils.ArchiveUtils.java

private static void zipEntry(File file, ZipOutputStream out, String delPath) throws IOException {
    if (file.isFile()) {
        FileInputStream in = new FileInputStream(file);
        out.putNextEntry(new ZipEntry(file.getPath().replace(delPath + File.separator, "")));
        IOUtils.copy(in, out);//  www .j a va 2s .co m

        out.closeEntry();
        IOUtils.closeQuietly(in);
    } else {
        for (File f : file.listFiles())
            zipEntry(f, out, delPath);
    }
}

From source file:com.ibm.amc.FileManager.java

private static void compressFile(File file, ZipOutputStream out, String basedir) {
    try {//from  w  w w . j  av a  2 s  . c  om
        BufferedInputStream bis = new BufferedInputStream(new FileInputStream(file));
        ZipEntry entry = new ZipEntry(basedir + file.getName());
        out.putNextEntry(entry);
        int length = Long.valueOf(file.length()).intValue();
        int buffer = ZIP_BUFFER;
        if (length != 0) {
            buffer = length;
        }
        int count;
        byte data[] = new byte[buffer];
        while ((count = bis.read(data, 0, buffer)) != -1) {
            out.write(data, 0, count);
        }
        bis.close();
    } catch (Exception e) {
        throw new AmcRuntimeException(e);
    }
}

From source file:com.plotsquared.iserver.util.FileUtils.java

/**
 * Add files to a zip file//ww w.  ja  va2s  .co m
 *
 * @param zipFile Zip File
 * @param files   Files to add to the zip
 * @param delete  If the original files should be deleted
 * @throws Exception If anything goes wrong
 */
public static void addToZip(final File zipFile, final File[] files, final boolean delete) throws Exception {
    Assert.notNull(zipFile, files);

    if (!zipFile.exists()) {
        if (!zipFile.createNewFile()) {
            throw new RuntimeException("Couldn't create " + zipFile);
        }
    }

    final File temporary = File.createTempFile(zipFile.getName(), "");
    //noinspection ResultOfMethodCallIgnored
    temporary.delete();

    if (!zipFile.renameTo(temporary)) {
        throw new RuntimeException("Couldn't rename " + zipFile + " to " + temporary);
    }

    final byte[] buffer = new byte[1024 * 16]; // 16mb

    ZipInputStream zis = new ZipInputStream(new FileInputStream(temporary));
    ZipOutputStream zos = new ZipOutputStream(new FileOutputStream(zipFile));

    ZipEntry e = zis.getNextEntry();
    while (e != null) {
        String n = e.getName();

        boolean no = true;
        for (File f : files) {
            if (f.getName().equals(n)) {
                no = false;
                break;
            }
        }

        if (no) {
            zos.putNextEntry(new ZipEntry(n));
            int len;
            while ((len = zis.read(buffer)) > 0) {
                zos.write(buffer, 0, len);
            }
        }
        e = zis.getNextEntry();
    }
    zis.close();
    for (File file : files) {
        InputStream in = new FileInputStream(file);
        zos.putNextEntry(new ZipEntry(file.getName()));

        int len;
        while ((len = in.read(buffer)) > 0) {
            zos.write(buffer, 0, len);
        }

        zos.closeEntry();
        in.close();
    }
    zos.close();
    temporary.delete();

    if (delete) {
        for (File f : files) {
            f.delete();
        }
    }
}