Android InputStream Zip compress(InputStream is, OutputStream os)

Here you can find the source of compress(InputStream is, OutputStream os)

Description

compress

License

Open Source License

Declaration

private static void compress(InputStream is, OutputStream os) 

Method Source Code


import java.io.*;

import java.util.zip.GZIPOutputStream;

public class Main {
    private static final int BUFFER = 1024;
    private static final String EXT = ".gz";

    @SuppressWarnings("UnusedDeclaration")
    public static byte[] compress(byte[] data) {
        ByteArrayInputStream bais = new ByteArrayInputStream(data);
        ByteArrayOutputStream baos = new ByteArrayOutputStream();

        /* www  .java 2s .c om*/
        compress(bais, baos);

        byte[] output = baos.toByteArray();

        try {
            baos.flush();
        } catch (IOException e) {
            System.out.println(e.getMessage());
        } finally {
            try {
                baos.close();
            } catch (IOException e) {
                
            }

            try {
                bais.close();
            } catch (IOException e) {
                
            }

        }

        return output;
    }

    @SuppressWarnings("UnusedDeclaration")
    public static void compress(File file) throws Exception {
        compress(file, true);
    }

    private static void compress(File file, boolean delete)
            throws Exception {
        FileInputStream fis = new FileInputStream(file);
        FileOutputStream fos = new FileOutputStream(file.getPath() + EXT);

        compress(fis, fos);

        fis.close();
        fos.flush();
        fos.close();

        if (delete) {
            
            file.delete();
        }
    }

    private static void compress(InputStream is, OutputStream os) {

        GZIPOutputStream gos = null;
        try {
            gos = new GZIPOutputStream(os);
            int count;
            byte data[] = new byte[BUFFER];
            while ((count = is.read(data, 0, BUFFER)) != -1) {
                gos.write(data, 0, count);
            }

            gos.finish();

            gos.flush();
        } catch (IOException e) {
            System.out.println(e.getMessage());
        } finally {
            try {
                if (gos != null) {
                    gos.close();
                }
            } catch (IOException e) {
                
            }
        }

    }

    @SuppressWarnings("UnusedDeclaration")
    public static void compress(String path) throws Exception {
        compress(path, true);
    }

    @SuppressWarnings("SameParameterValue")
    private static void compress(String path, boolean delete)
            throws Exception {
        File file = new File(path);
        compress(file, delete);
    }
}

Related

  1. unZipTo(InputStream paramInputStream, String paramString)
  2. compress(InputStream is, OutputStream os)
  3. compress(InputStream is, OutputStream os)