Java Zip File Check isZipFile(File file)

Here you can find the source of isZipFile(File file)

Description

A quick test to determine if uploaded file is a ZIP file

License

Open Source License

Parameter

Parameter Description
file the file to interrogate for being a zip file

Exception

Parameter Description
IOException an exception

Return

true is the specified file is a zip file

Declaration

public static boolean isZipFile(File file) throws IOException 

Method Source Code

//package com.java2s;
/*******************************************************************************
 * Copyright (c) 2015 CA.  All rights reserved.
 *
 * This source file is licensed under the terms of the Eclipse Public License 1.0
 * For the full text of the EPL please see https://www.eclipse.org/legal/epl-v10.html
 *******************************************************************************/

import java.io.File;
import java.io.FileInputStream;

import java.io.IOException;

import java.util.Arrays;

public class Main {
    private final static byte[] ZIP_SIGNATURE = { 'P', 'K', 0x03, 0x04 };

    /**//from  ww  w. j  a  v a2s .  c o  m
     * A quick test to determine if uploaded file is a ZIP file
     * <p> 
     * @param file the file to interrogate for being a zip file 
     * @return true is the specified file is a zip file
     * @throws IOException
     */
    public static boolean isZipFile(File file) throws IOException {

        boolean isZipFile = false;
        FileInputStream fileInputStream = null;

        try {

            fileInputStream = new FileInputStream(file);

            if (fileInputStream.available() > ZIP_SIGNATURE.length) {

                byte[] magic = new byte[ZIP_SIGNATURE.length];

                if (ZIP_SIGNATURE.length == fileInputStream.read(magic, 0, ZIP_SIGNATURE.length)) {

                    isZipFile = Arrays.equals(magic, ZIP_SIGNATURE);

                }

            }

        } finally {

            if (null != fileInputStream) {
                fileInputStream.close();
            }

        }

        return isZipFile;
    }
}

Related

  1. isZipFile(File file)
  2. isZipFile(File file)
  3. isZipFile(File file)
  4. isZipFile(File file)
  5. isZipFile(File file)
  6. isZipFile(File file)
  7. isZipFile(File file)
  8. isZipFile(File file)
  9. isZipFile(InputStream stream)