- Given the input files in java, create zip or compress files using ZipOutputStream class .
- Java framework has provided couple of classes to create a zip & compress file.
- ZipOutputStream: ZipOutputStream class implements an output stream filter for writing files in ZIP file format.
- ZipEntry: ZipEntry class represents a ZIP file entry.
- e.g. If we want to zip file named “FirstFile.txt”, then ZipEntry of “FirstFile.txt” shall be created.
1. Create compressed/zip file in java (ZipOutputStream/example)
- Suppose, we would like to zip three files named “FirstFile.txt”, “SecondFile.txt” and “ThirdFile.txt”.
- We create output zip file using ZipOutputStream class.
- Let us zip input file “FirstFile.txt” in java.
- We would like to zip first file named “FirstFile.txt”.
- We will create ZipEntry having name “FirstFile.txt”.
- We will put the ZipEntry object to ZipOutputStream i.e. zipped content representing “FirstFile.txt”.
- We will read contents of “FirstFile.txt” and write to to ZipOutputStream.
- We have successfully zipped “FirstFile.txt”.
- Similarly, we can zip others file using ZipOutputStream in java.
2. Create compressed /zip file in java (ZipOutputStream /example)
package org.learn;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Arrays;
import java.util.List;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;
public class ZipFilesInJava {
public static void main(String[] args) throws IOException {
//Path of output zip file
String outputZip = "C:\\ZipDirectory\\files.zip";
//Contents to be zipped.
List<File> files = Arrays.asList(
new File("C:\\ZipDirectory\\FirstFile.txt"),
new File("C:\\ZipDirectory\\SecondFile.txt"),
new File("C:\\ZipDirectory\\ThirdFile.txt")
);
System.out.println("1. Zipping the contents of input directory");
createZipFile(outputZip, files);
System.out.println("2. Successfully zipped contents");
}
private static void createZipFile(String outputZip, List<File> listOfFiles)
throws IOException {
//Create zip file
ZipOutputStream zipOutputStream = new ZipOutputStream(
new FileOutputStream(outputZip));
for (File file : listOfFiles) {
String fileName = file.getName();
//Read files
FileInputStream readFile = new FileInputStream(file);
//Create zip entry
ZipEntry zipEntry = new ZipEntry(fileName);
//Set zip entry
zipOutputStream.putNextEntry(zipEntry);
int readChar = -1;
while ((readChar = readFile.read()) != -1) {
zipOutputStream.write(readChar);
}
readFile.close();
zipOutputStream.closeEntry();
System.out.println("Zipping input file: "+fileName);
}
zipOutputStream.close();
}
}
3. Example: Create of zip of input files in java
4. Output – Create compressed /zip file in java (ZipOutputStream /example)
1. Zipping the contents of input directory
Zipping input file: FirstFile.txt
Zipping input file: SecondFile.txt
Zipping input file: ThirdFile.txt
2. Successfully zipped contents