Example usage for java.util.zip Deflater BEST_COMPRESSION

List of usage examples for java.util.zip Deflater BEST_COMPRESSION

Introduction

In this page you can find the example usage for java.util.zip Deflater BEST_COMPRESSION.

Prototype

int BEST_COMPRESSION

To view the source code for java.util.zip Deflater BEST_COMPRESSION.

Click Source Link

Document

Compression level for best compression.

Usage

From source file:Main.java

public static String compressGzipFile(String filename) {
    if (android.os.Environment.getExternalStorageState().equals(android.os.Environment.MEDIA_MOUNTED)) {

        File flockedFilesFolder = new File(
                Environment.getExternalStorageDirectory() + File.separator + "FlockLoad");
        System.out.println("FlockedFileDir: " + flockedFilesFolder);
        String uncompressedFile = flockedFilesFolder.toString() + "/" + filename;
        String compressedFile = flockedFilesFolder.toString() + "/" + "gzip.zip";

        try {//  w  ww .ja  v  a2 s .  c o  m
            FileInputStream fis = new FileInputStream(uncompressedFile);
            FileOutputStream fos = new FileOutputStream(compressedFile);
            GZIPOutputStream gzipOS = new GZIPOutputStream(fos) {
                {
                    def.setLevel(Deflater.BEST_COMPRESSION);
                }
            };

            byte[] buffer = new byte[1024];
            int len;
            while ((len = fis.read(buffer)) != -1) {
                gzipOS.write(buffer, 0, len);
            }
            //close resources
            gzipOS.close();
            fos.close();
            fis.close();
            return compressedFile;
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    return null;

}

From source file:org.ojbc.util.helper.ZipUtils.java

public static byte[] zip(byte[] originalData) {
    Deflater compressor = new Deflater();
    compressor.setLevel(Deflater.BEST_COMPRESSION);
    compressor.setInput(originalData);//  w  w  w. j  av a 2 s  .  c o  m
    compressor.finish();

    ByteArrayOutputStream bos = new ByteArrayOutputStream(originalData.length);

    byte[] buf = new byte[1024];
    while (!compressor.finished()) {
        int count = compressor.deflate(buf);
        bos.write(buf, 0, count);
    }

    try {
        bos.close();
    } catch (IOException e) {
        log.error("Failed to zip data " + originalData, e);
    }
    byte[] compressedData = bos.toByteArray();

    log.debug("Orignal data:" + originalData.length + " bytes");
    log.debug("Compressed data:" + compressedData.length + " bytes");
    return compressedData;
}

From source file:com.hundsun.jresplus.web.nosession.cookie.HessianZipSerializer.java

public static byte[] encode(Object object) throws SerializationException {
    if (object == null) {
        return null;
    }//from   ww  w . j  a  v  a  2s.  c  o m
    ByteArrayOutputStream baos = new ByteArrayOutputStream();

    Deflater def = new Deflater(Deflater.BEST_COMPRESSION, false);
    DeflaterOutputStream dos = new DeflaterOutputStream(baos, def);

    Hessian2Output ho = null;

    try {
        ho = new Hessian2Output(dos);
        ho.writeObject(object);
    } catch (Exception e) {
        throw new SerializationException("Failed to encode date", e);
    } finally {
        if (ho != null) {
            try {
                ho.close();
            } catch (IOException e) {
            }
        }
        try {
            dos.close();
        } catch (IOException e) {
        }

        def.end();
    }

    return baos.toByteArray();
}

From source file:org.apache.pig.impl.util.ObjectSerializer.java

public static String serialize(Serializable obj) throws IOException {
    if (obj == null)
        return "";
    try {/*from ww  w  .j a v  a 2s.c  o  m*/
        ByteArrayOutputStream serialObj = new ByteArrayOutputStream();
        Deflater def = new Deflater(Deflater.BEST_COMPRESSION);
        ObjectOutputStream objStream = new ObjectOutputStream(new DeflaterOutputStream(serialObj, def));
        objStream.writeObject(obj);
        objStream.close();
        return encodeBytes(serialObj.toByteArray());
    } catch (Exception e) {
        throw new IOException("Serialization error: " + e.getMessage(), e);
    }
}

From source file:Main.java

/**
 * Compress the byte array passed/*from   w  w w . j  ava  2s.  c  o m*/
 * <p>
 * @param input byte array
 * @param bufferLength buffer length
 * @return compressed byte array
 * @throws IOException thrown if we can't close the output stream
 */
public static byte[] compressByteArray(byte[] input, int bufferLength) throws IOException {
    // Compressor with highest level of compression
    Deflater compressor = new Deflater();
    compressor.setLevel(Deflater.BEST_COMPRESSION);

    // Give the compressor the data to compress
    compressor.setInput(input);
    compressor.finish();

    // Create an expandable byte array to hold the compressed data.
    // It is not necessary that the compressed data will be smaller than
    // the uncompressed data.
    ByteArrayOutputStream bos = new ByteArrayOutputStream(input.length);

    // Compress the data
    byte[] buf = new byte[bufferLength];
    while (!compressor.finished()) {
        int count = compressor.deflate(buf);
        bos.write(buf, 0, count);
    }

    // JCS-136 ( Details here : http://www.devguli.com/blog/eng/java-deflater-and-outofmemoryerror/ )
    compressor.end();
    bos.close();

    // Get the compressed data
    return bos.toByteArray();

}

From source file:com.qatickets.common.ZIPHelper.java

public static byte[] compress(byte[] data) {

    // Create the compressor with highest level of compression
    final Deflater compressor = new Deflater();
    compressor.setLevel(Deflater.BEST_COMPRESSION);

    // Give the compressor the data to compress
    compressor.setInput(data);// w w  w .  java2  s . com
    compressor.finish();

    // Create an expandable byte array to hold the compressed data.
    // You cannot use an array that's the same size as the orginal because
    // there is no guarantee that the compressed data will be smaller than
    // the uncompressed data.
    final ByteArrayOutputStream bos = new ByteArrayOutputStream(data.length);

    // Compress the data
    byte[] buf = new byte[1024];
    while (!compressor.finished()) {
        final int count = compressor.deflate(buf);
        bos.write(buf, 0, count);
    }
    try {
        bos.close();
    } catch (IOException e) {
    }

    // Get the compressed data
    final byte[] compressedData = bos.toByteArray();

    compressor.end();

    return compressedData;
}

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.
 * // w  ww  . j  av a2 s  .  c om
 * @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:org.getspout.spout.packet.PacketBlockData.java

public void compress() {
    if (!compressed) {
        Deflater deflater = new Deflater();
        deflater.setInput(data);// w w w  .j a v a  2 s  . c  o m
        deflater.setLevel(Deflater.BEST_COMPRESSION);
        deflater.finish();
        ByteArrayOutputStream bos = new ByteArrayOutputStream(data.length);
        byte[] buffer = new byte[1024];
        while (!deflater.finished()) {
            int bytesCompressed = deflater.deflate(buffer);
            bos.write(buffer, 0, bytesCompressed);
        }
        try {
            bos.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        data = bos.toByteArray();
        compressed = true;
    }
}

From source file:jetbrains.exodus.util.CompressBackupUtil.java

@NotNull
public static File backup(@NotNull final Backupable target, @NotNull final File backupRoot,
        @Nullable final String backupNamePrefix, final boolean zip) throws Exception {
    if (!backupRoot.exists() && !backupRoot.mkdirs()) {
        throw new IOException("Failed to create " + backupRoot.getAbsolutePath());
    }/*from w  ww  . ja v  a  2  s.  c  o m*/
    final File backupFile;
    final BackupStrategy strategy = target.getBackupStrategy();
    strategy.beforeBackup();
    try {
        final ArchiveOutputStream archive;
        if (zip) {
            final String fileName = getTimeStampedZipFileName();
            backupFile = new File(backupRoot,
                    backupNamePrefix == null ? fileName : backupNamePrefix + fileName);
            final ZipArchiveOutputStream zipArchive = new ZipArchiveOutputStream(
                    new BufferedOutputStream(new FileOutputStream(backupFile)));
            zipArchive.setLevel(Deflater.BEST_COMPRESSION);
            archive = zipArchive;
        } else {
            final String fileName = getTimeStampedTarGzFileName();
            backupFile = new File(backupRoot,
                    backupNamePrefix == null ? fileName : backupNamePrefix + fileName);
            archive = new TarArchiveOutputStream(
                    new GZIPOutputStream(new BufferedOutputStream(new FileOutputStream(backupFile))));
        }
        try (ArchiveOutputStream aos = archive) {
            for (final BackupStrategy.FileDescriptor fd : strategy.listFiles()) {
                if (strategy.isInterrupted()) {
                    break;
                }
                final File file = fd.getFile();
                if (file.isFile()) {
                    final long fileSize = Math.min(fd.getFileSize(), strategy.acceptFile(file));
                    if (fileSize > 0L) {
                        archiveFile(aos, fd.getPath(), file, fileSize);
                    }
                }
            }
        }
        if (strategy.isInterrupted()) {
            logger.info("Backup interrupted, deleting \"" + backupFile.getName() + "\"...");
            IOUtil.deleteFile(backupFile);
        } else {
            logger.info("Backup file \"" + backupFile.getName() + "\" created.");
        }
    } catch (Throwable t) {
        strategy.onError(t);
        throw ExodusException.toExodusException(t, "Backup failed");
    } finally {
        strategy.afterBackup();
    }
    return backupFile;
}

From source file:com.kolich.common.util.io.GZIPCompressor.java

/**
 * Given an uncompressed InputStream, compress it and return the
 * result as new byte array.//from  w  ww. j  a  va2s.  c o  m
 * @return
 */
public static final byte[] compress(final InputStream is, final int outputBufferSize) {
    GZIPOutputStream gzos = null;
    try {
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        gzos = new GZIPOutputStream(baos, outputBufferSize) {
            // Ugly anonymous constructor hack to set the compression
            // level on the underlying Deflater to "max compression".
            {
                def.setLevel(Deflater.BEST_COMPRESSION);
            }
        };
        IOUtils.copyLarge(is, gzos);
        gzos.finish();
        return baos.toByteArray();
    } catch (Exception e) {
        throw new GZIPCompressorException(e);
    } finally {
        closeQuietly(gzos);
    }
}