Java GZip Byte Array Check isGzipped(byte[] data)

Here you can find the source of isGzipped(byte[] data)

Description

Determines if the data contained in the buffer is gzipped by matching the first 2 bytes with GZIP magic GZIP_MAGIC (0x8b1f).

License

Open Source License

Parameter

Parameter Description
data a parameter

Declaration

public static boolean isGzipped(byte[] data) 

Method Source Code

//package com.java2s;
/*//  w w w.jav a 2  s.  c o  m
 * ***** BEGIN LICENSE BLOCK *****
 * Zimbra Collaboration Suite Server
 * Copyright (C) 2004, 2005, 2006, 2007, 2008, 2009, 2010, 2011, 2012, 2013, 2014, 2016 Synacor, Inc.
 *
 * This program is free software: you can redistribute it and/or modify it under
 * the terms of the GNU General Public License as published by the Free Software Foundation,
 * version 2 of the License.
 *
 * This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY;
 * without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
 * See the GNU General Public License for more details.
 * You should have received a copy of the GNU General Public License along with this program.
 * If not, see <https://www.gnu.org/licenses/>.
 * ***** END LICENSE BLOCK *****
 */

import java.io.IOException;
import java.io.InputStream;

import java.util.zip.GZIPInputStream;

public class Main {
    /**
     * Determines if the data contained in the buffer is gzipped
     * by matching the first 2 bytes with GZIP magic GZIP_MAGIC (0x8b1f).
     * @param data
     * @return
     */
    public static boolean isGzipped(byte[] data) {
        if (data == null || data.length < 2) {
            return false;
        }
        int byte1 = data[0];
        int byte2 = data[1] & 0xff; // Remove sign, since bytes are signed in Java.
        return (byte1 | (byte2 << 8)) == GZIPInputStream.GZIP_MAGIC;
    }

    /**
     * Determines if the data in the given stream is gzipped.
     * Requires that the <tt>InputStream</tt> supports mark/reset.
     */
    public static boolean isGzipped(InputStream in) throws IOException {
        in.mark(2);
        int header = in.read() | (in.read() << 8);
        in.reset();
        if (header == GZIPInputStream.GZIP_MAGIC) {
            return true;
        }
        return false;
    }
}

Related

  1. isGzip(byte[] bytes)
  2. isGZipped(byte[] bytes)