'Java: Telling whether a byte array is a zip file

I have a server written in Java, that in a single request, gets a whole file from the client. The file is passed to the server as a list of bytes, and is finally represented in the java server as a byte array.

Is there some standard way / standard library that could tell whether a file represented by a byte array is a valid zip file?



Solution 1:[1]

Files are typically identified using magic numbers in the beginning of the file.

To make an educated guess about a given file Java has built-in method of detecting some file types: Files.probeContentType. Plus, there are various third party libraries: simplemagic or Apache Tika (which supports more than only magic numbers).

But content detection alone won't tell you whether the file is valid. For that, you'd need something that actually knows how to read Zip files, such as Java's ZipFile.

Solution 2:[2]

If you want to standard way to implement for this process, you can use serialization API.For that use following articles that found myself while searching about this topic.

Article 1 - javaworld
Article 2 - developer.com

Solution 3:[3]

Check Zip4j library. It is really easy to use and the ZipFile class has a isValidZipFile() method

Solution 4:[4]

The easiest way is to check the "PK" magic at the beginning of the byte array.

Something like this:

"PK".equals(new String(array, 0,2))

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1
Solution 2 YMA
Solution 3
Solution 4 Faz