Checks if an input stream is gzipped. - Java File Path IO

Java examples for File Path IO:GZIP

Description

Checks if an input stream is gzipped.

Demo Code

/*//from w  w w  . ja  va 2 s . c om
 * Copyright 2014 davidherod.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
//package com.java2s;

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

import java.util.zip.GZIPInputStream;

public class Main {
    /**
     * Checks if an input stream is gzipped.
     *
     * @param in
     * @return
     */
    public static InputStream decompressStream(InputStream input)
            throws IOException {
        PushbackInputStream pb = new PushbackInputStream(input, 2); //we need a pushbackstream to look ahead
        byte[] signature = new byte[2];
        pb.read(signature); //read the signature
        pb.unread(signature); //push back the signature to the stream
        if (signature[0] == (byte) 0x1f && signature[1] == (byte) 0x8b) //check if matches standard gzip maguc number
        {
            return new GZIPInputStream(pb);
        } else {
            return pb;
        }
    }
}

Related Tutorials