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:io.fabric8.support.impl.SupportServiceImpl.java

private void safeClose(ZipOutputStream zip) {
    if (zip != null) {
        try {/*  w w w  .ja  va2s. com*/
            zip.closeEntry();
        } catch (IOException e) {
            LOGGER.debug("Error while closing ZIP entry", e);
        }
    }
}

From source file:com.epam.wilma.message.search.web.support.FileZipper.java

private void addFileToZipStream(final ZipOutputStream zipStream, final String fileName, final InputStream file)
        throws IOException {
    putZipEntryToStream(zipStream, fileName);
    IOUtils.copy(file, zipStream);/*from  w ww  .  ja  v a  2  s .c o m*/
    zipStream.closeEntry();
}

From source file:org.bonitasoft.engine.io.IOUtil.java

/**
 * Create a structured zip archive recursively.
 * The string must be OS specific String to represent path.
 *
 *//*ww w  . ja  va2 s  .co  m*/
public static void zipDir(final String dir2zip, final ZipOutputStream zos, final String root)
        throws IOException {
    final File zipDir = new File(dir2zip);
    final byte[] readBuffer = new byte[BUFFER_SIZE];

    for (final String pathName : zipDir.list()) {
        final File file = new File(zipDir, pathName);
        final String path = file.getPath();
        if (file.isDirectory()) {
            zipDir(path, zos, root);
            continue;
        }
        try {
            final ZipEntry anEntry = new ZipEntry(path.substring(root.length() + 1, path.length())
                    .replace(String.valueOf(File.separatorChar), "/"));
            zos.putNextEntry(anEntry);
            copyFileToZip(zos, readBuffer, file);
            zos.flush();
        } finally {
            zos.closeEntry();
        }
    }
}

From source file:nz.co.fortytwo.freeboard.server.util.ZipUtils.java

/**
 * Add the directory recursively into a zip file
 * @param zout/* ww  w .j  a  va  2  s. com*/
 * @param fileSource
 * @param sourceDir
 */
private static void addDirectory(ZipOutputStream zout, File fileSource, File sourceDir) {

    // get sub-folder/files list
    File[] files = fileSource.listFiles();

    logger.debug("Adding directory " + fileSource.getName());

    for (int i = 0; i < files.length; i++) {
        try {
            String name = files[i].getAbsolutePath();
            name = name.substring((int) sourceDir.getAbsolutePath().length());
            // if the file is directory, call the function recursively
            if (files[i].isDirectory()) {
                addDirectory(zout, files[i], sourceDir);
                continue;
            }

            /*
             * we are here means, its file and not directory, so
             * add it to the zip file
             */

            if (logger.isDebugEnabled())
                logger.debug("Adding file " + files[i].getName());

            // create object of FileInputStream
            FileInputStream fin = new FileInputStream(files[i]);

            zout.putNextEntry(new ZipEntry(name));

            IOUtils.copy(fin, zout);

            zout.closeEntry();

            // close the InputStream
            fin.close();

        } catch (IOException ioe) {
            logger.error(ioe.getMessage(), ioe);
        }
    }

}

From source file:ZipUtilInPlaceTest.java

public void testByteArrayTransformer() throws IOException {
    final String name = "foo";
    final byte[] contents = "bar".getBytes();

    File file1 = File.createTempFile("temp", null);
    try {//from  w  ww .  ja  v a  2 s. c om
        // Create the ZIP file
        ZipOutputStream zos = new ZipOutputStream(new FileOutputStream(file1));
        try {
            zos.putNextEntry(new ZipEntry(name));
            zos.write(contents);
            zos.closeEntry();
        } finally {
            IOUtils.closeQuietly(zos);
        }

        // Transform the ZIP file
        ZipUtil.transformEntry(file1, name, new ByteArrayZipEntryTransformer() {
            protected byte[] transform(ZipEntry zipEntry, byte[] input) throws IOException {
                String s = new String(input);
                assertEquals(new String(contents), s);
                return s.toUpperCase().getBytes();
            }
        });

        // Test the ZipUtil
        byte[] actual = ZipUtil.unpackEntry(file1, name);
        assertNotNull(actual);
        assertEquals(new String(contents).toUpperCase(), new String(actual));
    } finally {
        FileUtils.deleteQuietly(file1);
    }
}

From source file:org.apache.hadoop.streaming.TestMultipleArchiveFiles.java

protected void createInput() throws IOException {
    fileSys.delete(new Path(INPUT_DIR), true);
    DataOutputStream dos = fileSys.create(new Path(INPUT_FILE));
    String inputFileString = "symlink1" + File.separator + "cacheArchive1\nsymlink2" + File.separator
            + "cacheArchive2";
    dos.write(inputFileString.getBytes("UTF-8"));
    dos.close();//  ww w .  j a  v  a  2 s  . c  om

    DataOutputStream out = fileSys.create(new Path(CACHE_ARCHIVE_1.toString()));
    ZipOutputStream zos = new ZipOutputStream(out);
    ZipEntry ze = new ZipEntry(CACHE_FILE_1.toString());
    zos.putNextEntry(ze);
    zos.write(input.getBytes("UTF-8"));
    zos.closeEntry();
    zos.close();

    out = fileSys.create(new Path(CACHE_ARCHIVE_2.toString()));
    zos = new ZipOutputStream(out);
    ze = new ZipEntry(CACHE_FILE_2.toString());
    zos.putNextEntry(ze);
    zos.write(input.getBytes("UTF-8"));
    zos.closeEntry();
    zos.close();
}

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

/**
 * Compress multiple Files with the given encoding.
 *
 * @param logFiles     files to be compressed
 * @param fromEncoding log file encoding
 * @param toEncoding   compressed log file encoding
 * @return compressed file byte array/*  ww w . ja  va2  s  .  c  o  m*/
 */
public static byte[] compress(File[] logFiles, Charset fromEncoding, Charset toEncoding) {
    FileInputStream fis = null;
    InputStreamReader isr = null;
    ByteArrayOutputStream out = null;
    ZipOutputStream zos = null;
    OutputStreamWriter osw = null;
    if (toEncoding == null) {
        toEncoding = Charset.defaultCharset();
    }
    if (fromEncoding == null) {
        fromEncoding = Charset.defaultCharset();
    }
    try {
        out = new ByteArrayOutputStream();
        zos = new ZipOutputStream(out);
        osw = new OutputStreamWriter(zos, toEncoding);
        for (File each : logFiles) {
            try {
                fis = new FileInputStream(each);
                isr = new InputStreamReader(fis, fromEncoding);
                ZipEntry zipEntry = new ZipEntry(each.getName());
                zipEntry.setTime(each.lastModified());
                zos.putNextEntry(zipEntry);
                char[] buffer = new char[COMPRESS_BUFFER_SIZE];
                int count;
                while ((count = isr.read(buffer, 0, COMPRESS_BUFFER_SIZE)) != -1) {
                    osw.write(buffer, 0, count);
                }
                osw.flush();
                zos.flush();
                zos.closeEntry();
            } catch (IOException e) {
                LOGGER.error("Error occurs while compressing {} : {}", each.getAbsolutePath(), e.getMessage());
                LOGGER.debug("Details ", e);
            } finally {
                IOUtils.closeQuietly(isr);
                IOUtils.closeQuietly(fis);
            }
        }
        zos.finish();
        zos.flush();
        return out.toByteArray();
    } catch (IOException e) {
        LOGGER.error("Error occurs while compressing log : {} ", e.getMessage());
        LOGGER.debug("Details : ", e);
        return null;
    } finally {
        IOUtils.closeQuietly(zos);
        IOUtils.closeQuietly(out);
        IOUtils.closeQuietly(osw);
    }
}

From source file:nz.ac.otago.psyanlab.common.util.FileUtils.java

/**
 * Copies assets files referenced in experiment to the specified archive.
 * /*from  w w  w .j  ava 2s. c  o  m*/
 * @param archive Archive to copy assets into.
 * @param experiment The experiment.
 * @return Modified experiment file with updated asset references.
 * @throws IOException
 */
private static Experiment copyAssetsToArchive(ZipOutputStream out, Experiment experiment, File workingDir)
        throws IOException {

    for (Entry<Long, Asset> entry : experiment.assets.entrySet()) {
        long key = entry.getKey();
        Asset asset = entry.getValue();
        File assetFile;
        if (asset.isExternal()) {
            assetFile = new File(asset.path);
        } else {
            assetFile = new File(workingDir, asset.path);
        }
        InputStream in = new FileInputStream(assetFile);

        // Rename files so as to prevent name collision.
        String newPath = "assets/" + asset.getTypeId() + "_" + key;
        ZipEntry ze = new ZipEntry(newPath);
        out.putNextEntry(ze);

        // Update definition with new asset location.
        asset.path = newPath;
        experiment.assets.put(key, asset);

        try {
            copy(in, out);
            out.closeEntry();
        } finally {
            in.close();
        }
    }

    for (Entry<Long, Source> entry : experiment.sources.entrySet()) {
        long key = entry.getKey();
        Source source = entry.getValue();
        File assetFile;
        if (source.isExternal()) {
            assetFile = new File(source.path);
        } else {
            assetFile = new File(workingDir, source.path);
        }
        InputStream in = new FileInputStream(assetFile);

        // Rename files so as to prevent name collision.
        String newPath = "sources/" + key;
        ZipEntry ze = new ZipEntry(newPath);
        out.putNextEntry(ze);

        // Update definition with new asset location.
        source.path = newPath;
        experiment.sources.put(key, source);

        try {
            copy(in, out);
            out.closeEntry();
        } finally {
            in.close();
        }
    }

    return experiment;
}

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  . c  o  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:com.jaspersoft.jasperserver.jrsh.common.ZipUtil.java

protected static void addFiles(ZipOutputStream zos, String folder, String baseFolder) throws Exception {
    File file = new File(folder);
    if (file.exists()) {
        if (file.isDirectory()) {
            if (!folder.equalsIgnoreCase(baseFolder)) {
                String entryName = folder.substring(baseFolder.length() + 1, folder.length()) + separatorChar;
                ZipEntry zipEntry = new ZipEntry(entryName);
                zos.putNextEntry(zipEntry);
            }/*from  w  w  w.  j  a  v a2  s.  co  m*/
            File files[] = file.listFiles();
            if (files != null) {
                for (File f : files) {
                    addFiles(zos, f.getAbsolutePath(), baseFolder);
                }
            }
        } else {
            String entryName = folder.substring(baseFolder.length() + 1, folder.length());
            ZipEntry zipEntry = new ZipEntry(entryName);
            zos.putNextEntry(zipEntry);

            try (FileInputStream in = new FileInputStream(folder)) {
                int len;
                byte buf[] = new byte[1024];
                while ((len = in.read(buf)) > 0) {
                    zos.write(buf, 0, len);
                }
                zos.closeEntry();
            }
        }
    }
}