Java GZip gzip(final T o)

Here you can find the source of gzip(final T o)

Description

passed object convert to gziped byte array.

License

Open Source License

Parameter

Parameter Description
o a parameter

Exception

Parameter Description
JSONException an exception
IOException an exception

Declaration

public static final <T> byte[] gzip(final T o) throws IOException 

Method Source Code

//package com.java2s;
//License from project: Open Source License 

import java.io.BufferedWriter;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;

import java.io.OutputStreamWriter;
import java.nio.file.Files;

import java.util.zip.GZIPOutputStream;
import com.fasterxml.jackson.databind.ObjectMapper;

public class Main {
    private static final ObjectMapper MAPPER = new ObjectMapper();

    /**// ww  w .  ja v a2 s.  com
     * passed object convert to gziped byte array.
     * @param o
     * @return
     * @throws JSONException
     * @throws IOException
     */
    public static final <T> byte[] gzip(final T o) throws IOException {
        if (o == null) {
            return null;
        }
        try (final ByteArrayOutputStream baos = new ByteArrayOutputStream();
                final GZIPOutputStream gzip = new GZIPOutputStream(baos);) {
            gzip.write(MAPPER.writeValueAsBytes(o));
            ;
            gzip.close();
            return baos.toByteArray();
        }
    }

    /**
     * write to gzip file.
     * @param o
     * @param filename
     * @throws IOException
     */
    public static void write(final Object o, final String filename) throws IOException {
        try (final BufferedWriter bw = setUpWriter(filename)) {
            bw.write(MAPPER.writeValueAsString(o));
            bw.close();
        }
    }

    /**
     * set up gzip file writer.
     * @param filename
     * @return
     * @throws IOException
     */
    private static BufferedWriter setUpWriter(final String filename) throws IOException {
        return new BufferedWriter(
                new OutputStreamWriter(new GZIPOutputStream(Files.newOutputStream(new File(filename).toPath()))));
    }
}

Related

  1. gzip(String s)
  2. gzip(String str)
  3. gzipDecompress(byte[] compressed)
  4. gzipFileReader(String file)