package org.kodejava.util.zip;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;
public class ZippingFileExample {
public static void main(String[] args) {
String source = "data.txt";
String target = "data.zip";
try (ZipOutputStream zos =
new ZipOutputStream(new FileOutputStream(target));
InputStream is =
ZippingFileExample.class.getResourceAsStream("/" + source)) {
if (is != null) {
// Put a new ZipEntry in the ZipOutputStream
zos.putNextEntry(new ZipEntry(source));
int size;
byte[] buffer = new byte[1024];
// Read data to the end of the source file and write it
// to the zip output stream.
while ((size = is.read(buffer, 0, buffer.length)) > 0) {
zos.write(buffer, 0, size);
}
zos.closeEntry();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
Latest posts by Wayan (see all)
- How do I create a string of repeated characters? - September 1, 2023
- How do I convert datetime string with optional part to a date object? - August 28, 2023
- How do I split large excel file into multiple smaller files? - April 15, 2023