Create ZIP File Using try with Resources in Java
Create the ZIP
ZIP file generation in java is straight forward. You need a ZipOutputStream
that takes a FileOutputStream
witch takes the output name of the file. Using this with try with resources is very clever because we don’t need to handle the closing of our streams. The JVM handles this for us witch results in cleaner and more readable code. After our ZipOutputStream
is created we Iterate over the files that needs to be added to the zip and read them using FileInputStream then with the .putNextEntry()
we add it to the ZIP file. When the streams are read the JVM will close those streams automatically.
package com.memorynotfound.zip;
import java.io.*;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;
public class Zip {
public static void create(String name, File... files) throws IOException {
// temporary byte buffer used for copying data from one stream to the other
byte[] buffer = new byte[1024];
try (ZipOutputStream zipFile = new ZipOutputStream(new FileOutputStream(name))){
for (File file : files){
FileInputStream fileIn = new FileInputStream(file);
zipFile.putNextEntry(new ZipEntry(name));
zipFile.setMethod(ZipOutputStream.DEFLATED);
zipFile.setLevel(5);
// keeps track of the number of bytes successfully read
int lenRead = 0;
// copy content of inputStream to zipFile
while((lenRead = fileIn.read(buffer)) > 0){
zipFile.write(buffer, 0, lenRead);
}
}
// streams will be closed automatically because they are within the try-resource block
}
}
}
Sample Use Case
We are testing the ZIP with one example.txt file that we’ll write to example.zip
package com.memorynotfound.zip;
import java.io.File;
import java.io.IOException;
public class ZipProgram {
public static void main(String... args) throws IOException {
File file = new File(ZipProgram.class.getResource("/example.txt").getFile());
Zip.create("example.zip", file);
}
}