Example usage for org.apache.commons.compress.archivers.zip ZipArchiveOutputStream ZipArchiveOutputStream

List of usage examples for org.apache.commons.compress.archivers.zip ZipArchiveOutputStream ZipArchiveOutputStream

Introduction

In this page you can find the example usage for org.apache.commons.compress.archivers.zip ZipArchiveOutputStream ZipArchiveOutputStream.

Prototype

public ZipArchiveOutputStream(File file) throws IOException 

Source Link

Document

Creates a new ZIP OutputStream writing to a File.

Usage

From source file:cz.muni.fi.xklinec.zipstream.App.java

/**
 * Entry point. /*from   www  .ja  va  2  s.c o m*/
 * 
 * @param args
 * @throws FileNotFoundException
 * @throws IOException
 * @throws NoSuchFieldException
 * @throws ClassNotFoundException
 * @throws NoSuchMethodException 
 */
public static void main(String[] args) throws FileNotFoundException, IOException, NoSuchFieldException,
        ClassNotFoundException, NoSuchMethodException, InterruptedException {
    OutputStream fos = null;
    InputStream fis = null;

    if ((args.length != 0 && args.length != 2)) {
        System.err.println(String.format("Usage: app.jar source.apk dest.apk"));
        return;
    } else if (args.length == 2) {
        System.err.println(
                String.format("Will use file [%s] as input file and [%s] as output file", args[0], args[1]));
        fis = new FileInputStream(args[0]);
        fos = new FileOutputStream(args[1]);
    } else if (args.length == 0) {
        System.err.println(String.format("Will use file [STDIN] as input file and [STDOUT] as output file"));
        fis = System.in;
        fos = System.out;
    }

    final Deflater def = new Deflater(9, true);
    ZipArchiveInputStream zip = new ZipArchiveInputStream(fis);

    // List of postponed entries for further "processing".
    List<PostponedEntry> peList = new ArrayList<PostponedEntry>(6);

    // Output stream
    ZipArchiveOutputStream zop = new ZipArchiveOutputStream(fos);
    zop.setLevel(9);

    // Read the archive
    ZipArchiveEntry ze = zip.getNextZipEntry();
    while (ze != null) {

        ZipExtraField[] extra = ze.getExtraFields(true);
        byte[] lextra = ze.getLocalFileDataExtra();
        UnparseableExtraFieldData uextra = ze.getUnparseableExtraFieldData();
        byte[] uextrab = uextra != null ? uextra.getLocalFileDataData() : null;

        // ZipArchiveOutputStream.DEFLATED
        // 

        // Data for entry
        byte[] byteData = Utils.readAll(zip);
        byte[] deflData = new byte[0];
        int infl = byteData.length;
        int defl = 0;

        // If method is deflated, get the raw data (compress again).
        if (ze.getMethod() == ZipArchiveOutputStream.DEFLATED) {
            def.reset();
            def.setInput(byteData);
            def.finish();

            byte[] deflDataTmp = new byte[byteData.length * 2];
            defl = def.deflate(deflDataTmp);

            deflData = new byte[defl];
            System.arraycopy(deflDataTmp, 0, deflData, 0, defl);
        }

        System.err.println(String.format(
                "ZipEntry: meth=%d " + "size=%010d isDir=%5s " + "compressed=%07d extra=%d lextra=%d uextra=%d "
                        + "comment=[%s] " + "dataDesc=%s " + "UTF8=%s " + "infl=%07d defl=%07d " + "name [%s]",
                ze.getMethod(), ze.getSize(), ze.isDirectory(), ze.getCompressedSize(),
                extra != null ? extra.length : -1, lextra != null ? lextra.length : -1,
                uextrab != null ? uextrab.length : -1, ze.getComment(),
                ze.getGeneralPurposeBit().usesDataDescriptor(), ze.getGeneralPurposeBit().usesUTF8ForNames(),
                infl, defl, ze.getName()));

        final String curName = ze.getName();

        // META-INF files should be always on the end of the archive, 
        // thus add postponed files right before them
        if (curName.startsWith("META-INF") && peList.size() > 0) {
            System.err.println(
                    "Now is the time to put things back, but at first, I'll perform some \"facelifting\"...");

            // Simulate som evil being done
            Thread.sleep(5000);

            System.err.println("OK its done, let's do this.");
            for (PostponedEntry pe : peList) {
                System.err.println(
                        "Adding postponed entry at the end of the archive! deflSize=" + pe.deflData.length
                                + "; inflSize=" + pe.byteData.length + "; meth: " + pe.ze.getMethod());

                pe.dump(zop, false);
            }

            peList.clear();
        }

        // Capturing interesting files for us and store for later.
        // If the file is not interesting, send directly to the stream.
        if ("classes.dex".equalsIgnoreCase(curName) || "AndroidManifest.xml".equalsIgnoreCase(curName)) {
            System.err.println("### Interesting file, postpone sending!!!");

            PostponedEntry pe = new PostponedEntry(ze, byteData, deflData);
            peList.add(pe);
        } else {
            // Write ZIP entry to the archive
            zop.putArchiveEntry(ze);
            // Add file data to the stream
            zop.write(byteData, 0, infl);
            zop.closeArchiveEntry();
        }

        ze = zip.getNextZipEntry();
    }

    // Cleaning up stuff
    zip.close();
    fis.close();

    zop.finish();
    zop.close();
    fos.close();

    System.err.println("THE END!");
}

From source file:com.hw.util.CompressUtils.java

public static final void zip(String compressPath, String[] needCompressPaths) {
    File compressFile = new File(compressPath);

    List<File> files = new ArrayList<File>();
    for (String needCompressPath : needCompressPaths) {
        File needCompressFile = new File(needCompressPath);
        if (!needCompressFile.exists()) {
            continue;
        }/*from  w  w  w. ja va  2  s.c  o  m*/
        files.add(needCompressFile);
    }
    try {
        ZipArchiveOutputStream zaos = null;
        try {
            zaos = new ZipArchiveOutputStream(compressFile);
            zaos.setUseZip64(Zip64Mode.AsNeeded);
            zaos.setEncoding("GBK");

            for (File file : files) {
                addFilesToCompression(zaos, file, "");
            }

        } catch (IOException e) {
            throw e;
        } finally {
            IOUtils.closeQuietly(zaos);
        }
    } catch (Exception e) {
        FileUtils.deleteQuietly(compressFile);
        throw new RuntimeException("", e);
    }
}

From source file:com.daphne.es.maintain.editor.web.controller.utils.CompressUtils.java

public static final void zip(String compressPath, String[] needCompressPaths) {
    File compressFile = new File(compressPath);

    List<File> files = Lists.newArrayList();
    for (String needCompressPath : needCompressPaths) {
        File needCompressFile = new File(needCompressPath);
        if (!needCompressFile.exists()) {
            continue;
        }//from  w w  w  . j ava 2 s .  c  om
        files.add(needCompressFile);
    }
    try {
        ZipArchiveOutputStream zaos = null;
        try {
            zaos = new ZipArchiveOutputStream(compressFile);
            zaos.setUseZip64(Zip64Mode.AsNeeded);
            zaos.setEncoding("GBK");

            for (File file : files) {
                addFilesToCompression(zaos, file, "");
            }

        } catch (IOException e) {
            throw e;
        } finally {
            IOUtils.closeQuietly(zaos);
        }
    } catch (Exception e) {
        FileUtils.deleteQuietly(compressFile);
        throw new RuntimeException("", e);
    }
}

From source file:com.haulmont.cuba.core.sys.logging.LogArchiver.java

public static void writeArchivedLogTailToStream(File logFile, OutputStream outputStream) throws IOException {
    if (!logFile.exists()) {
        throw new FileNotFoundException();
    }//from w  w  w  .ja  v  a 2 s.  co m

    ZipArchiveOutputStream zipOutputStream = new ZipArchiveOutputStream(outputStream);
    zipOutputStream.setMethod(ZipArchiveOutputStream.DEFLATED);
    zipOutputStream.setEncoding(ZIP_ENCODING);

    byte[] content = getTailBytes(logFile);

    ArchiveEntry archiveEntry = newTailArchive(logFile.getName(), content);
    zipOutputStream.putArchiveEntry(archiveEntry);
    zipOutputStream.write(content);

    zipOutputStream.closeArchiveEntry();
    zipOutputStream.close();
}

From source file:edu.jhu.hlt.acute.archivers.zip.ZipArchiver.java

/**
 * Wrap an {@link Path} that represents a 
 * <code>.zip</code> file. This constructor be used when writing to files on disk.
 * /*from   w  w  w  . j av a2s  .c  o m*/
 * @throws IOException 
 */
public ZipArchiver(Path path) throws IOException {
    this.zout = new ZipArchiveOutputStream(path.toFile());
}

From source file:au.org.ala.biocache.util.AlaFileUtils.java

/**
 * Creates a zip file at the specified path with the contents of the specified directory.
 * NB://from  w w  w .  j a  v  a  2 s.c  o  m
 *
 * @param directoryPath The path of the directory where the archive will be created. eg. c:/temp
 * @param zipPath The full path of the archive to create. eg. c:/temp/archive.zip
 * @throws IOException If anything goes wrong
 */
public static void createZip(String directoryPath, String zipPath) throws IOException {
    FileOutputStream fOut = null;
    BufferedOutputStream bOut = null;
    ZipArchiveOutputStream tOut = null;

    try {
        fOut = new FileOutputStream(new File(zipPath));
        bOut = new BufferedOutputStream(fOut);
        tOut = new ZipArchiveOutputStream(bOut);
        addFileToZip(tOut, directoryPath, "");
    } finally {
        tOut.finish();
        tOut.close();
        bOut.close();
        fOut.close();
    }
}

From source file:com.openkm.util.ArchiveUtils.java

/**
 * Create ZIP archive from file/*  www  . java 2s  .  c  om*/
 */
public static void createZip(File path, OutputStream os) throws IOException {
    log.debug("createZip({}, {})", new Object[] { path, os });

    if (path.exists() && path.canRead()) {
        ZipArchiveOutputStream zaos = new ZipArchiveOutputStream(os);
        zaos.setComment("Generated by OpenKM");
        zaos.setCreateUnicodeExtraFields(UnicodeExtraFieldPolicy.ALWAYS);
        zaos.setUseLanguageEncodingFlag(true);
        zaos.setFallbackToUTF8(true);
        zaos.setEncoding("UTF-8");

        log.debug("FILE {}", path);
        ZipArchiveEntry zae = new ZipArchiveEntry(path.getName());
        zaos.putArchiveEntry(zae);
        FileInputStream fis = new FileInputStream(path);
        IOUtils.copy(fis, zaos);
        fis.close();
        zaos.closeArchiveEntry();

        zaos.flush();
        zaos.finish();
        zaos.close();
    } else {
        throw new IOException("Can't access " + path);
    }

    log.debug("createZip: void");
}

From source file:com.ikon.util.ArchiveUtils.java

/**
 * Recursively create ZIP archive from directory 
 *///  w  w  w.j av  a 2s. c  o m
public static void createZip(File path, String root, OutputStream os) throws IOException {
    log.debug("createZip({}, {}, {})", new Object[] { path, root, os });

    if (path.exists() && path.canRead()) {
        ZipArchiveOutputStream zaos = new ZipArchiveOutputStream(os);
        zaos.setComment("Generated by openkm");
        zaos.setCreateUnicodeExtraFields(UnicodeExtraFieldPolicy.ALWAYS);
        zaos.setUseLanguageEncodingFlag(true);
        zaos.setFallbackToUTF8(true);
        zaos.setEncoding("UTF-8");

        // Prevents java.util.zip.ZipException: ZIP file must have at least one entry
        ZipArchiveEntry zae = new ZipArchiveEntry(root + "/");
        zaos.putArchiveEntry(zae);
        zaos.closeArchiveEntry();

        createZipHelper(path, zaos, root);

        zaos.flush();
        zaos.finish();
        zaos.close();
    } else {
        throw new IOException("Can't access " + path);
    }

    log.debug("createZip: void");
}

From source file:aiai.apps.commons.utils.ZipUtils.java

/**
 * Creates a zip file at the specified path with the contents of the specified directory.
 * NB://from w  w  w  . j a  v  a  2  s  . co m
 *
 * @param directory The path of the directory where the archive will be created. eg. c:/temp
 * @param zipFile zip file
 * @throws IOException If anything goes wrong
 */
public static void createZip(File directory, File zipFile) throws IOException {

    try (FileOutputStream fOut = new FileOutputStream(zipFile);
            BufferedOutputStream bOut = new BufferedOutputStream(fOut);
            ZipArchiveOutputStream tOut = new ZipArchiveOutputStream(bOut)) {
        addFileToZip(tOut, directory, "");
    }
}

From source file:edu.jhu.hlt.acute.archivers.zip.ZipArchiver.java

/**
 * Wrap an {@link OutputStream}. //ww w  .  j  a  v a  2s  . co m
 * <br/>
 * <br/>
 * Do not use this constructor if the {@link OutputStream} is writing to a file. 
 * Use {@link #ZipArchiver(Path)} instead. 
 * 
 * @param out an {@link OutputStream}
 * @see #ZipArchiver(Path)
 */
public ZipArchiver(OutputStream out) {
    this.zout = new ZipArchiveOutputStream(out);
}