Java GZip File Check isGZipped(String name)

Here you can find the source of isGZipped(String name)

Description

Returns true if file is in GZip format and false if it is not.

License

Open Source License

Parameter

Parameter Description
String the path to the file

Return

boolean true for GZip format; false if not

Declaration

public final static boolean isGZipped(String name) 

Method Source Code

//package com.java2s;
/**/*from  w ww .j  a  v  a2 s.  c om*/
 * Copyright (C) 2013-2017
 * Jeffrey Fulmer - <jeff@joedog.org>, et al.
 *
 * 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; either version 2 of the License, or
 * (at your option) any later version.
 *
 * 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, write to the Free Software Foundation, Inc.
 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
 *--
 */

import java.io.File;

import java.io.RandomAccessFile;

import java.util.zip.GZIPInputStream;

public class Main {
    /**
     * Returns true if file is in GZip format and 
     * false if it is not. 
     * <p>
     * @param  String   the path to the file
     * @return boolean  true for GZip format; false if not
     */
    public final static boolean isGZipped(String name) {
        int n = 0;
        File file = null;
        RandomAccessFile raf = null;
        try {
            try {
                file = new File(name);
                if (!file.exists()) {
                    return false;
                }
                raf = new RandomAccessFile(file, "r");
                n = raf.read() & 0xff | ((raf.read() << 8) & 0xff00);
            } finally {
                if (raf != null) {
                    raf.close();
                }
            }
        } catch (Throwable e) {
            e.printStackTrace(System.err);
        }
        return n == GZIPInputStream.GZIP_MAGIC;
    }

    /**
     * Test whether or not a file or directory denoted by 
     * the parameter exists. Returns false if the input is 
     * null or if the resource cannot be located.
     * <p>
     * @ param   String  The name of the file or directory
     * @ return  boolean
     */
    public final static boolean exists(String name) {
        File file;
        if (name == null) {
            return false;
        }
        file = new File(name);
        return file.exists();
    }
}

Related

  1. isGzipped(File file)
  2. isGZipped(final File f)
  3. isGzipped(final File file)
  4. isGZipped(final File file)
  5. isGzipped(String fileName)