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 find Java version? - March 21, 2022
- How do I convert CSV to JSON string using Jackson? - February 13, 2022
- How do I convert CSV file to or from JSON file? - February 13, 2022