Java
javaTutorial
Detailed explanation of ZipException in Java_Handling scenarios where the compressed package format is illegal or the password is incorrect
Detailed explanation of ZipException in Java_Handling scenarios where the compressed package format is illegal or the password is incorrect
ZipException is mainly caused by file damage or encryption without providing a password. You need to use system tools to verify the validity of the file first, and then check the Java API usage, JDK version and third-party library password processing logic.

ZipException is the most commonly thrown exception when the compressed package cannot be opened.
When encountering ZipException in Java, there are basically two reasons: the file is not in a legal ZIP format at all (for example, it is truncated, damaged, it is actually RAR/7z but the suffix has been changed), or the ZIP is encrypted but no password is given or the password is wrong. It won’t tell you which one it is, and will only throw out vague hints such as “invalid CEN header” or “zip file is empty”, which will make people suspect that they have written the code wrong.
Practical suggestions:
- Don't rush to change the Java code - first use the system's built-in decompression tool (such as macOS's archive utility, Windows' resource manager) to manually open the file and verify whether it can actually be decompressed; if the system tool also reports an error, the problem lies in the source file itself
- If the file can be opened normally by system tools, then check whether Java uses the wrong API: for example, using
ZipInputStreamto read volume ZIP (ZipFiledoes not support volume,ZipInputStreamdoes not work), or an unresetInputStreamis passed in (for example, half of the HTTP response body is read and then used to constructZipInputStream) - Pay attention to the differences in JDK versions: JDK 9 has stricter support for the ZIP64 extension. The older version can just read the damaged ZIP, but the new version may directly throw
ZipException
Typical error messages and locating methods of ZipException when the password is incorrect
The standard JDK java.util.zip package ** does not support encrypted ZIP** at all, so as long as you see ZipException and involve passwords (for example, the error message contains "encrypted", "PK Bad CRC", "invalid entry size"), it means that you have actually used a third-party library (such as net.lingala.zip4j or org.apache.commons.compress ), but did not handle the password logic correctly.
Common errors:
- Use
ZipFileto open a ZIP with password → directly throwZipException: error in opening zip file(it's not that the password is wrong, it's that JDK doesn't recognize the encryption format at all) - Use
Zip4jbut callextractAll()without callingsetPassword()→ reportZipException: Unsupported Zip Version [20]orCRC mismatch - The password string uses the wrong encoding (for example, the original password is GBK-encoded Chinese, but
"UTF-8"is used to constructchar[]) → After decryption, the data is messed up, andZipException: invalid stored block lengthstriggered during subsequent reading.
Practical suggestions:
- Confirm which library you are using: check
pom.xmlor build script. The APIs ofzip4jandcommons-compressare completely different. Mixing them will cause explosion. - For
zip4j,setPassword(new Password("xxx"))must be adjusted afterZipFileis instantiated and before decompression; if the password is an empty string, it must be set explicitly and cannot be skipped. - When testing, give priority to using pure ASCII passwords (such as
"123456") to eliminate coding interference; switch back to the real password after confirming that it is correct.
How to distinguish between ZIP corruption and incorrect password? Relying on try-catch is not enough
Simply catching ZipException and printing the message cannot distinguish whether the file is damaged or the password is incorrect, because both may throw similar underlying errors (such as "invalid entry size" or "CRC failed" ). The truly reliable way to judge is through layered testing.
Practical suggestions:
- Step 1: Use
FileInputStreamZipInputStreamto read only the metadata of the first entry in the ZIP (without decompressing the content) and see if you can successfully callgetNextEntry(); if it fails, it is most likely that the format is illegal or the file is damaged. - Step 2: If the metadata is readable, try to read the first few bytes of the first entry (
read(buf, 0, 8)); if -1 is returned or an exception is thrown, it may be that the password error caused the stream to be interrupted early. - Step 3: For known encrypted ZIP, force the decryptor to be initialized with the correct password (such as
zip4j'sZipParameters), and then callisValidZipFile()- this method will verify the central directory structure and expose problems earlier than blind decompression.
ZipException is more likely to trigger compatibility traps on Android
The ZIP implementation of the Android system (especially the old version) has extremely low tolerance for ZIP64, data descriptors, and non-standard compression algorithms (such as LZMA). The same ZIP can be opened in the desktop JDK, but it will consistently throw ZipException: unknown format on Android.
Practical suggestions:
- Avoid using
java.util.zip.ZipFileon Android to read ZIP generated by WinRAR / 7-Zip; usezip4jfirst and enable compatibility mode:new ZipFile(file).setCharset(StandardCharsets.UTF_8)config.setSupportZip64(true) - When the server generates ZIP, clearly specify the compression tool and parameters: use
jarcommand or JDK'sZipOutputStream, disable ZIP64 (unless the file > 4GB), turn off the data descriptor (setUseDataDescriptor(false)) - If the ZIP is uploaded from a user, be sure to do a pre-check on the server side: adjust
size()immediately after constructing it withZipFile, catch the exception and return a friendly prompt (such as "The file may be damaged, please re-upload") instead of crashing the client
The real trouble is never the exception type itself, but the loose ZIP format specifications, different tool implementations, and inconsistent encryption schemes - the same ZIP file may behave completely differently in different environments, different libraries, and different JDK versions. When processing, always validate input first before suspecting code.
The above is the detailed content of Detailed explanation of ZipException in Java_Handling scenarios where the compressed package format is illegal or the password is incorrect. For more information, please follow other related articles on the PHP Chinese website!
Hot AI Tools
Undress AI Tool
Undress images for free
AI Clothes Remover
Online AI tool for removing clothes from photos.
Undresser.AI Undress
AI-powered app for creating realistic nude photos
ArtGPT
AI image generator for creative art from text prompts.
Stock Market GPT
AI powered investment research for smarter decisions
Hot Article
Popular tool
Notepad++7.3.1
Easy-to-use and free code editor
SublimeText3 Chinese version
Chinese version, very easy to use
Zend Studio 13.0.1
Powerful PHP integrated development environment
Dreamweaver CS6
Visual web development tools
SublimeText3 Mac version
God-level code editing software (SublimeText3)
Hot Topics
20606
7
13699
4
How to configure Spark distributed computing environment in Java_Java big data processing
Mar 09, 2026 pm 08:45 PM
Spark cannot run in local mode, ClassNotFoundException: org.apache.spark.sql.SparkSession. This is the most common first step of getting stuck: even the dependencies are not correct. Only spark-core_2.12 is written in Maven, but spark-sql_2.12 is not added. SparkSession crashes as soon as it is built. The Scala version must strictly match the official Spark compiled version - Spark3.4.x uses Scala2.12 by default. If you use spark-sqljar of 2.13, the class loader cannot directly find the main class. Practical advice: Go to mvnre
What is exception masking (Suppressed Exceptions) in Java_Multiple resource shutdown exception handling
Mar 10, 2026 pm 06:57 PM
What is SuppressedException: It is not "swallowed", but actively archived by the JVM. SuppressedException is not an exception loss, but the JVM quietly attaches the secondary exception to the main exception under the premise that "only one exception must be thrown" for you to verify afterwards. It is automatically triggered by the JVM in only two scenarios: one is that the resource closure in try-with-resources fails, and the other is that you manually call addSuppressed() in finally. The key difference is: the former is fully automatic and safe; the latter requires you to keep it to yourself, and it can be written as shadowing if you are not careful. try-
How to safely map user-entered weekday string to integer value and implement date offset operation in Java
Mar 09, 2026 pm 09:43 PM
This article introduces a concise and maintainable way to map the weekday string (such as "Monday") to the corresponding serial number (1-7), and use the modulo operation to realize the forward and backward offset of any number of days (such as Monday plus 4 days to get Friday), avoiding lengthy if chains and hard-coded logic.
How to configure Java's log output environment_Logback and Log4j2 integration solution
Mar 10, 2026 pm 08:39 PM
They cannot be used together - Logback and Log4j2 are mutually exclusive, and SLF4J only allows one binding to take effect; if they exist at the same time, a warning will be triggered and one of them will be randomly selected, resulting in log loss or abnormal behavior. A unified appearance and single implementation are required.
How to use Homebrew to install Java on Mac_A must-have Java tool chain for developers
Mar 09, 2026 pm 09:48 PM
Homebrew installs the latest stable version of openjdk (such as JDK22) by default, not the LTS version; you need to explicitly execute brewinstallopenjdk@17 or brewinstallopenjdk@21 to install the LTS version, and manually configure PATH and JAVA_HOME to be correctly recognized by the system and IDE.
How to deploy Java production environment on Windows Server_Security enhancement and service-oriented configuration
Mar 11, 2026 pm 07:18 PM
The boundary between Java version selection and JRE/JDK must be clearly defined in the production environment. Do not use JDK. JRE must be installed on Windows Server—unless you really need diagnostic tools such as jps and jstack to run in the service process. The java.exe and javaw.exe that come with the JDK have the same behavior, but the extra bin directory in the JDK will increase the attack surface. Especially when misconfigured PATH causes the script to call javac.exe, it may be used to execute compiled malicious payloads. Download the build with jdk-xx.jre suffix from https://adoptium.net/ (such as temurin-17.0.2 8-jre), which is not the jdk package installation path.
Complete tutorial on reading data from file and initializing two-dimensional array in Java
Mar 09, 2026 pm 09:18 PM
This article explains in detail how to load an integer sequence in an external text file into a Java two-dimensional array according to a specified row and column structure (such as 2500×100), avoiding manual assignment or index out-of-bounds, and ensuring accurate data order and robust and reusable code.
What is the underlying principle of array expansion in Java_Java memory dynamic adjustment analysis
Mar 09, 2026 pm 09:45 PM
ArrayList.add() triggers expansion because grow() is called when size is equal to elementData.length. The first add allocates 10 capacity, and subsequent expansion is 1.5 times and not less than the minimum requirement, relying on delayed initialization and System.arraycopy optimization.





