How to Zip and Unzip Files and Folders in Java
import java.util.zip.*;
import java.io.*;
public class ZipTool {
public static void zipMyFile( String inputFile, String outputFile ) throws IOException, FileNotFoundException {
ZipOutputStream zo = new ZipOutputStream(new FileOutputStream(outputFile));
FileInputStream fi = new FileInputStream(new File(inputFile));
ZipEntry ze = new ZipEntry(inputFile);
zo.putNextEntry(ze);
byte[] buf = new byte[1024];
int length;
while((length = fi.read(buf)) >= 0) {
zo.write(buf, 0, length);
}
zo.close();
fi.close();
}
public static void zipSomeFiles(String[] inputFileList, String outputFile) throws IOException, FileNotFoundException {
ZipOutputStream zo = new ZipOutputStream(new FileOutputStream(outputFile));
for ( String f1 : inputFileList ) {
FileInputStream fi = new FileInputStream(new File(f1));
ZipEntry ze = new ZipEntry(f1);
zo.putNextEntry(ze);
byte[] buf = new byte[1024];
int length;
while((length = fi.read(buf)) >= 0) {
zo.write(buf, 0, length);
}
fi.close();
}
zo.close();
}
public static void main(String[] args) throws IOException, FileNotFoundException {
zipMyFile("test.txt", "test.txt.zip");
String[] srcFiles = new String[]{new String("test1.txt"), new String("test2.txt")};
zipSomeFiles(srcFiles, "test_B.zip");
}
}