Java provides the ZipInputStream class for reading from a zip file. Heres a general example of its usage
File file = new File("my.zip");
ZipInputStream zin = new ZipInputStream(new FileInputStream(file));
ZipEntry ze = null;
while ((ze = zin.getNextEntry()) != null) {
String filename = ze.getName();
if (!ze.isDirectory()) {
// Read file contents from 'zin'
// For example you could read from zin and write it to a FileOutputStream
// https://helpdesk.objects.com.au/java/how-do-i-copy-one-stream-to-another-using-java
}
zin.closeEntry();
}
zin.close();
The same can be used to read the contents of a jar file.
written by objects
\\ tags: decompress, file, stream, unzip, zip, ZipInputStream
// Create the ZIP file
ZipOutputStream out = new ZipOutputStream(new FileOutputStream("my.zip"));
// loop through the files to add to zip
for (int i=0; i<filenames.length; i++)
{
// open file
FileInputStream in = new FileInputStream(filenames[i]);
// Add new entry to zip
out.putNextEntry(new ZipEntry(filenames[i]));
// copy file to zip
// see https://helpdesk.objects.com.au/java/how-do-i-copy-one-stream-to-another-using-java
int len;
while ((len = in.read(buf)) >= 0)
{
out.write(buf, 0, len);
}
// Close the entry and file
out.closeEntry();
in.close();
}
// Close the ZIP file
out.close();
written by objects
\\ tags: file, zip, ZipOutputStream
If you get the following error when trying to read a valid zip file using Java it may be because it contains an entry larger than 4gb.
java.util.zip.ZipException: invalid CEN header
Java’s implementation of Java only support entries smaller than 4gb. To read a zip file that contains entries larger than 4gb you will need to use a 3rd pary implementation such as Zip64
written by objects
\\ tags: zip, zip64, ZipEntry, ZipFile