Avoid Creating Empty ZIP or JAR Files
ID |
java.create_empty_zip_jar |
Severity |
low |
Remediation Complexity |
medium |
Remediation Risk |
low |
Remediation Effort |
medium |
Resource |
Code Smell |
Language |
Java |
Tags |
code-style, reliability |
Description
Reports creation of ZipOutputStream or JarOutputStream in methods that never call putNextEntry().
Rationale
Opening a ZIP or JAR output stream and closing it without writing any entries creates an invalid or empty archive file. This wastes I/O resources and the resulting file may cause errors in downstream consumers that expect valid archive contents.
// Bad - creates an empty (invalid) zip file
ZipOutputStream zos = new ZipOutputStream(new FileOutputStream("out.zip"));
zos.close();
Remediation
Ensure at least one entry is written before closing the stream, or remove the unnecessary stream creation.
// Good - writes an entry before closing
ZipOutputStream zos = new ZipOutputStream(new FileOutputStream("out.zip"));
zos.putNextEntry(new ZipEntry("data.txt"));
zos.write(data);
zos.closeEntry();
zos.close();