Example usage for java.util.zip ZipEntry setMethod

List of usage examples for java.util.zip ZipEntry setMethod

Introduction

In this page you can find the example usage for java.util.zip ZipEntry setMethod.

Prototype

public void setMethod(int method) 

Source Link

Document

Sets the compression method for the entry.

Usage

From source file:com.smash.revolance.ui.model.helper.ArchiveHelper.java

public static File buildArchive(File archive, File... files) throws FileNotFoundException {
    FileOutputStream fos = new FileOutputStream(archive);
    ZipOutputStream zos = new ZipOutputStream(fos);
    int bytesRead;
    byte[] buffer = new byte[1024];
    CRC32 crc = new CRC32();

    for (File file : files) {
        if (!file.exists()) {
            System.err.println("Skipping: " + file);
            continue;
        }//from  w  w  w .j ava 2s .  c  o m
        BufferedInputStream bis = null;
        try {
            bis = new BufferedInputStream(new FileInputStream(file));
            crc.reset();
            while ((bytesRead = bis.read(buffer)) != -1) {
                crc.update(buffer, 0, bytesRead);
            }

            bis.close();

            // Reset to beginning of input stream
            bis = new BufferedInputStream(new FileInputStream(file));
            String entryPath = FileHelper.getRelativePath(archive.getParentFile(), file);

            ZipEntry entry = new ZipEntry(entryPath);
            entry.setMethod(ZipEntry.STORED);
            entry.setCompressedSize(file.length());
            entry.setSize(file.length());
            entry.setCrc(crc.getValue());
            zos.putNextEntry(entry);
            while ((bytesRead = bis.read(buffer)) != -1) {
                zos.write(buffer, 0, bytesRead);
            }
        } catch (FileNotFoundException e) {

        } catch (IOException e) {
            e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates.
        } finally {
            IOUtils.closeQuietly(bis);
        }
    }
    IOUtils.closeQuietly(zos);
    return archive;
}

From source file:net.sf.jabref.exporter.OpenDocumentSpreadsheetCreator.java

private static void storeOpenDocumentSpreadsheetFile(File file, InputStream source) throws Exception {

    try (ZipOutputStream out = new ZipOutputStream(new BufferedOutputStream(new FileOutputStream(file)))) {

        //addResourceFile("mimetype", "/resource/ods/mimetype", out);
        ZipEntry ze = new ZipEntry("mimetype");
        String mime = "application/vnd.oasis.opendocument.spreadsheet";
        ze.setMethod(ZipEntry.STORED);
        ze.setSize(mime.length());// w w  w. j  a v a2s .  c  o  m
        CRC32 crc = new CRC32();
        crc.update(mime.getBytes());
        ze.setCrc(crc.getValue());
        out.putNextEntry(ze);
        for (int i = 0; i < mime.length(); i++) {
            out.write(mime.charAt(i));
        }
        out.closeEntry();

        ZipEntry zipEntry = new ZipEntry("content.xml");
        //zipEntry.setMethod(ZipEntry.DEFLATED);
        out.putNextEntry(zipEntry);
        int c;
        while ((c = source.read()) >= 0) {
            out.write(c);
        }
        out.closeEntry();

        // Add manifest (required for OOo 2.0) and "meta.xml": These are in the
        // resource/ods directory, and are copied verbatim into the zip file.
        OpenDocumentSpreadsheetCreator.addResourceFile("meta.xml", "/resource/ods/meta.xml", out);

        OpenDocumentSpreadsheetCreator.addResourceFile("META-INF/manifest.xml", "/resource/ods/manifest.xml",
                out);
    }
}

From source file:com.diffplug.gradle.ZipMisc.java

/**
 * Modifies only the specified entries in a zip file. 
 *
 * @param input       a source from a zip file
 * @param output      an output to a zip file
 * @param toModify      a map from path to an input stream for the entries you'd like to change
 * @param toOmit      a set of entries you'd like to leave out of the zip
 * @throws IOException//from  w  w w.j  a  va 2 s  . c o m
 */
public static void modify(ByteSource input, ByteSink output, Map<String, Function<byte[], byte[]>> toModify,
        Predicate<String> toOmit) throws IOException {
    try (ZipInputStream zipInput = new ZipInputStream(input.openBufferedStream());
            ZipOutputStream zipOutput = new ZipOutputStream(output.openBufferedStream())) {
        while (true) {
            // read the next entry
            ZipEntry entry = zipInput.getNextEntry();
            if (entry == null) {
                break;
            }

            Function<byte[], byte[]> replacement = toModify.get(entry.getName());
            if (replacement != null) {
                byte[] clean = ByteStreams.toByteArray(zipInput);
                byte[] modified = replacement.apply(clean);
                // if it's the entry being modified, enter the modified stuff
                try (InputStream replacementStream = new ByteArrayInputStream(modified)) {
                    ZipEntry newEntry = new ZipEntry(entry.getName());
                    newEntry.setComment(entry.getComment());
                    newEntry.setExtra(entry.getExtra());
                    newEntry.setMethod(entry.getMethod());
                    newEntry.setTime(entry.getTime());

                    zipOutput.putNextEntry(newEntry);
                    copy(replacementStream, zipOutput);
                }
            } else if (!toOmit.test(entry.getName())) {
                // if it isn't being modified, just copy the file stream straight-up
                ZipEntry newEntry = new ZipEntry(entry);
                newEntry.setCompressedSize(-1);
                zipOutput.putNextEntry(newEntry);
                copy(zipInput, zipOutput);
            }

            // close the entries
            zipInput.closeEntry();
            zipOutput.closeEntry();
        }
    }
}

From source file:JarUtils.java

/**
 * This recursive method writes all matching files and directories to
 * the jar output stream.//from  ww w .  j  a v  a2  s  .c om
 */
private static void jar(File src, String prefix, JarInfo info) throws IOException {

    JarOutputStream jout = info.out;
    if (src.isDirectory()) {
        // create / init the zip entry
        prefix = prefix + src.getName() + "/";
        ZipEntry entry = new ZipEntry(prefix);
        entry.setTime(src.lastModified());
        entry.setMethod(JarOutputStream.STORED);
        entry.setSize(0L);
        entry.setCrc(0L);
        jout.putNextEntry(entry);
        jout.closeEntry();

        // process the sub-directories
        File[] files = src.listFiles(info.filter);
        for (int i = 0; i < files.length; i++) {
            jar(files[i], prefix, info);
        }
    } else if (src.isFile()) {
        // get the required info objects
        byte[] buffer = info.buffer;

        // create / init the zip entry
        ZipEntry entry = new ZipEntry(prefix + src.getName());
        entry.setTime(src.lastModified());
        jout.putNextEntry(entry);

        // dump the file
        FileInputStream in = new FileInputStream(src);
        int len;
        while ((len = in.read(buffer, 0, buffer.length)) != -1) {
            jout.write(buffer, 0, len);
        }
        in.close();
        jout.closeEntry();
    }
}

From source file:eionet.gdem.utils.ZipUtil.java

/**
 *
 * @param f// w w  w.  j  a  v  a2s .c o  m
 *            - File that will be zipped
 * @param outZip
 *            - ZipOutputStream represents the zip file, where the files will be placed
 * @param sourceDir
 *            - root directory, where the zipping started
 * @param doCompress
 *            - don't comress the file, if doCompress=true
 * @throws IOException If an error occurs.
 */
public static void zipFile(File f, ZipOutputStream outZip, String sourceDir, boolean doCompress)
        throws IOException {

    // Read the source file into byte array
    byte[] fileBytes = Utils.getBytesFromFile(f);

    // create a new zip entry
    String strAbsPath = f.getPath();
    String strZipEntryName = strAbsPath.substring(sourceDir.length() + 1, strAbsPath.length());
    strZipEntryName = Utils.Replace(strZipEntryName, File.separator, "/");
    ZipEntry anEntry = new ZipEntry(strZipEntryName);

    // Don't compress the file, if not needed
    if (!doCompress) {
        // ZipEntry can't calculate crc size automatically, if we use STORED method.
        anEntry.setMethod(ZipEntry.STORED);
        anEntry.setSize(fileBytes.length);
        CRC32 crc321 = new CRC32();
        crc321.update(fileBytes);
        anEntry.setCrc(crc321.getValue());
    }
    // place the zip entry in the ZipOutputStream object
    outZip.putNextEntry(anEntry);

    // now write the content of the file to the ZipOutputStream
    outZip.write(fileBytes);

    outZip.flush();
    // Close the current entry
    outZip.closeEntry();

}

From source file:brut.directory.ZipUtils.java

private static void processFolder(final File folder, final ZipOutputStream zipOutputStream,
        final int prefixLength) throws BrutException, IOException {
    for (final File file : folder.listFiles()) {
        if (file.isFile()) {
            final String cleanedPath = BrutIO.sanitizeUnknownFile(folder,
                    file.getPath().substring(prefixLength));
            final ZipEntry zipEntry = new ZipEntry(BrutIO.normalizePath(cleanedPath));

            // aapt binary by default takes in parameters via -0 arsc to list extensions that shouldn't be
            // compressed. We will replicate that behavior
            final String extension = FilenameUtils.getExtension(file.getAbsolutePath());
            if (mDoNotCompress != null
                    && (mDoNotCompress.contains(extension) || mDoNotCompress.contains(zipEntry.getName()))) {
                zipEntry.setMethod(ZipEntry.STORED);
                zipEntry.setSize(file.length());
                BufferedInputStream unknownFile = new BufferedInputStream(new FileInputStream(file));
                CRC32 crc = BrutIO.calculateCrc(unknownFile);
                zipEntry.setCrc(crc.getValue());
                unknownFile.close();//from  www.j  ava  2  s. co m
            } else {
                zipEntry.setMethod(ZipEntry.DEFLATED);
            }

            zipOutputStream.putNextEntry(zipEntry);
            try (FileInputStream inputStream = new FileInputStream(file)) {
                IOUtils.copy(inputStream, zipOutputStream);
            }
            zipOutputStream.closeEntry();
        } else if (file.isDirectory()) {
            processFolder(file, zipOutputStream, prefixLength);
        }
    }
}

From source file:net.librec.util.FileUtil.java

/**
 * Zip a given folder//w w  w .java  2s  .c o m
 *
 * @param dirPath    a given folder: must be all files (not sub-folders)
 * @param filePath   zipped file
 * @throws Exception if error occurs
 */
public static void zipFolder(String dirPath, String filePath) throws Exception {
    File outFile = new File(filePath);
    ZipOutputStream zos = new ZipOutputStream(new FileOutputStream(outFile));
    int bytesRead;
    byte[] buffer = new byte[1024];
    CRC32 crc = new CRC32();
    for (File file : listFiles(dirPath)) {
        BufferedInputStream bis = new BufferedInputStream(new FileInputStream(file));
        crc.reset();
        while ((bytesRead = bis.read(buffer)) != -1) {
            crc.update(buffer, 0, bytesRead);
        }
        bis.close();

        // Reset to beginning of input stream
        bis = new BufferedInputStream(new FileInputStream(file));
        ZipEntry entry = new ZipEntry(file.getName());
        entry.setMethod(ZipEntry.STORED);
        entry.setCompressedSize(file.length());
        entry.setSize(file.length());
        entry.setCrc(crc.getValue());
        zos.putNextEntry(entry);
        while ((bytesRead = bis.read(buffer)) != -1) {
            zos.write(buffer, 0, bytesRead);
        }
        bis.close();
    }
    zos.close();

    LOG.debug("A zip-file is created to: " + outFile.getPath());
}

From source file:Main.java

public void doZip(String filename, String zipfilename) throws Exception {
    byte[] buf = new byte[1024];
    FileInputStream fis = new FileInputStream(filename);
    fis.read(buf, 0, buf.length);// ww  w  . jav a  2s.c  o  m

    CRC32 crc = new CRC32();
    ZipOutputStream s = new ZipOutputStream((OutputStream) new FileOutputStream(zipfilename));
    s.setLevel(6);

    ZipEntry entry = new ZipEntry(filename);
    entry.setSize((long) buf.length);
    entry.setMethod(ZipEntry.DEFLATED);
    crc.reset();
    crc.update(buf);
    entry.setCrc(crc.getValue());
    s.putNextEntry(entry);
    s.write(buf, 0, buf.length);
    s.finish();
    s.close();
}

From source file:gov.nih.nci.caarray.application.fileaccess.FileAccessUtils.java

/**
 * Adds the given file to the given zip output stream using the given name as the zip entry name. This method will
 * NOT call finish on the zip output stream at the end.
 * //from   ww  w  . j  a v a  2 s.com
 * @param zos the zip output stream to add the file to. This stream must already be open.
 * @param file the file to put in the zip.
 * @param name the name to use for this zip entry.
 * @param addAsStored if true, then the file will be added to the zip as a STORED entry (e.g. without applying
 *            compression to it); if false, then the file will be added to the zip as a DEFLATED entry.
 * @throws IOException if there is an error writing to the stream
 */
public void writeZipEntry(ZipOutputStream zos, File file, String name, boolean addAsStored) throws IOException {
    final ZipEntry ze = new ZipEntry(name);
    ze.setMethod(addAsStored ? ZipEntry.STORED : ZipEntry.DEFLATED);
    if (addAsStored) {
        ze.setSize(file.length());
        ze.setCrc(FileUtils.checksumCRC32(file));
    }
    zos.putNextEntry(ze);
    final InputStream is = FileUtils.openInputStream(file);
    IOUtils.copy(is, zos);
    zos.closeEntry();
    zos.flush();
    IOUtils.closeQuietly(is);
}

From source file:com.aionlightning.slf4j.conversion.TruncateToZipFileAppender.java

/**
 * This method creates archive with file instead of deleting it.
 * //from  ww w .j  av  a  2s  . c o  m
 * @param file
 *            file to truncate
 */
protected void truncate(File file) {
    File backupRoot = new File(backupDir);
    if (!backupRoot.exists() && !backupRoot.mkdirs()) {
        log.warn("Can't create backup dir for backup storage");
        return;
    }

    String date = "";
    try {
        BufferedReader reader = new BufferedReader(new FileReader(file));
        date = reader.readLine().split("\f")[1];
        reader.close();
    } catch (IOException e) {
        e.printStackTrace();
    }

    File zipFile = new File(backupRoot, file.getName() + "." + date + ".zip");
    ZipOutputStream zos = null;
    FileInputStream fis = null;
    try {
        zos = new ZipOutputStream(new FileOutputStream(zipFile));
        ZipEntry entry = new ZipEntry(file.getName());
        entry.setMethod(ZipEntry.DEFLATED);
        entry.setCrc(FileUtils.checksumCRC32(file));
        zos.putNextEntry(entry);
        fis = FileUtils.openInputStream(file);

        byte[] buffer = new byte[1024];
        int readed;
        while ((readed = fis.read(buffer)) != -1) {
            zos.write(buffer, 0, readed);
        }

    } catch (Exception e) {
        log.warn("Can't create zip file", e);
    } finally {
        if (zos != null) {
            try {
                zos.close();
            } catch (IOException e) {
                log.warn("Can't close zip file", e);
            }
        }

        if (fis != null) {
            try {
                fis.close();
            } catch (IOException e) {
                log.warn("Can't close zipped file", e);
            }
        }
    }

    if (!file.delete()) {
        log.warn("Can't delete old log file " + file.getAbsolutePath());
    }
}