Java Zip File Check isZip(File zip)

Here you can find the source of isZip(File zip)

Description

Check to see if the file is a zip file.

The ZIP file format can be determined by detecting #MAGIC_BYTES at the start of the zip file.

License

Open Source License

Parameter

Parameter Description
zip The file to check

Exception

Parameter Description
IOException an exception

Return

true if the file is a zip file, false otherwise

Declaration

public static boolean isZip(File zip) throws IOException 

Method Source Code


//package com.java2s;
/*/*from w  ww. ja va  2  s. com*/
Weave (Web-based Analysis and Visualization Environment)
Copyright (C) 2008-2014 University of Massachusetts Lowell
    
This file is a part of Weave.
    
Weave is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License, Version 3,
as published by the Free Software Foundation.
    
Weave 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 Weave.  If not, see <http://www.gnu.org/licenses/>.
*/

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

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

public class Main {
    public static final byte[] MAGIC_BYTES = { 'P', 'K', 0x3, 0x4 };

    /**
     * Check to see if the file is a zip file.<br><br>
     * The ZIP file format can be determined by detecting  
     * {@link #MAGIC_BYTES} at the start of the zip file.
     * 
     * @param zip The file to check
     * @return <code>true</code> if the file is a zip file, <code>false</code> otherwise
     * @throws IOException
     */
    public static boolean isZip(File zip) throws IOException {
        byte[] buffer = new byte[MAGIC_BYTES.length];

        if (zip == null)
            throw new NullPointerException("Zip file is null");

        assert zip != null;

        // If the file is a directory, it surely isn't a zip
        if (zip.isDirectory())
            return false;

        InputStream in = new DataInputStream(new FileInputStream(zip));
        in.read(buffer);
        in.close();

        for (int i = 0; i < buffer.length; i++)
            if (buffer[i] != MAGIC_BYTES[i])
                return false;
        return true;
    }
}

Related

  1. isZip(File f)
  2. isZip(File file)
  3. isZip(File file)
  4. isZip(File file)
  5. isZip(File file)
  6. isZip64EndOfCentralDirectoryLocatorPresent(RandomAccessFile zip, long zipEndOfCentralDirectoryPosition)
  7. isZipContainsEntry(File zip, String relativePath)
  8. isZipEntryPackage(String str)
  9. isZipFile(File f)