Java Tutorial/File/ZipOutputStream
Compressing Streams: Zipper, Java example
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;
public class Main {
public static void main(String[] args) throws IOException {
String outputFile = "a.zip";
int level = 9;
FileOutputStream fout = new FileOutputStream(outputFile);
ZipOutputStream zout = new ZipOutputStream(fout);
zout.setLevel(level);
ZipEntry ze = new ZipEntry("a.zip");
FileInputStream fin = new FileInputStream("b.dat");
zout.putNextEntry(ze);
for (int c = fin.read(); c != -1; c = fin.read()) {
zout.write(c);
}
fin.close();
zout.close();
}
}
Create ZipOutputStream from FileOutputStream
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;
public class MainClass {
public static void main(String[] args) throws IOException {
String outputFile = "new.zip";
// Default to maximum compression
int level = 9;
int start = 1;
FileOutputStream fout = new FileOutputStream(outputFile);
ZipOutputStream zout = new ZipOutputStream(fout);
zout.setLevel(level);
for (int i = start; i < args.length; i++) {
ZipEntry ze = new ZipEntry(args[i]);
FileInputStream fin = new FileInputStream(args[i]);
try {
System.out.println("Compressing " + args[i]);
zout.putNextEntry(ze);
for (int c = fin.read(); c != -1; c = fin.read()) {
zout.write(c);
}
} finally {
fin.close();
}
}
zout.close();
}
}