Best way to detect if a stream is zipped in Java

Viewed 23460

What is the best way to find out i java.io.InputStream contains zipped data?

7 Answers

Since both .zip and .xlsx having the same Magic number, I couldn't find the valid zip file (if renamed).

So, I have used Apache Tika to find the exact document type.

Even if renamed the file type as zip, it finds the exact type.

Reference: https://www.baeldung.com/apache-tika

I combined answers from @McDowell and @Innokenty to a small lib function that you can paste into you project:

public static boolean isZipStream(InputStream inputStream) {
    if (inputStream == null || !inputStream.markSupported()) {
        throw new IllegalArgumentException("InputStream must support mark-reset. Use BufferedInputstream()");
    }
    boolean isZipped = false;
    try {
        inputStream.mark(2048);
        isZipped = new ZipInputStream(inputStream).getNextEntry() != null;
        inputStream.reset();
    } catch (IOException ex) {
        // cannot be opend as zip.
    }
    return isZipped;
}

You can use the lib like this:

public static void main(String[] args) {
    InputStream inputStream = new BufferedInputStream(...);

    if (isZipStream(inputStream)) {
        // do zip processing using inputStream
    } else {
        // do non-zip processing using inputStream
    }

}
Related