Use the java.util.zip package for reading and writing ZIP files, including compressing and decompressing file entries.
Source Code
// Compressing a file
try (ZipOutputStream zos = new ZipOutputStream(new FileOutputStream("archive.zip"))) {
ZipEntry entry = new ZipEntry("filename.txt");
zos.putNextEntry(entry);
byte[] data = "Hello, World!".getBytes();
zos.write(data, 0, data.length);
zos.closeEntry();
} catch (IOException e) {
e.printStackTrace();
}
// Decompressing a file
try (ZipInputStream zis = new ZipInputStream(new FileInputStream("archive.zip"))) {
ZipEntry entry = zis.getNextEntry();
while (entry != null) {
System.out.println("Extracting: " + entry.getName());
FileOutputStream fos = new FileOutputStream(entry.getName());
int len;
byte[] buffer = new byte[1024];
while ((len = zis.read(buffer)) > 0) {
fos.write(buffer, 0, len);
}
fos.close();
entry = zis.getNextEntry();
}
zis.closeEntry();
} catch (IOException e) {
e.printStackTrace();
}