In Java 8 you can extract Zip–files to the local file system using the classes in java.util.zip. However plugging the building blocks together for the first time is not so easy. Many helpful examples on how to extract Zip–files in Java exist.
In my case I had a Zip–file included in a jar file as an embedded resource. So I wanted to extract files from a Zip–stream rather than from a Zip–file. This requires the use of different Classes from java.util.zip. Nice examples for this use case were much less frequent, so I created my own. This is it:
import java.io.*;
import java.util.zip.ZipEntry;
import java.util.zip.ZipInputStream;
public class ZipUtils {
/**
* @param source zip stream
* @param target target directory
* @throws IOException extraction failed
*/
public static void unzip(InputStream source, File target) throws IOException {
final ZipInputStream zipStream = new ZipInputStream(source);
ZipEntry nextEntry;
while ((nextEntry = zipStream.getNextEntry()) != null) {
final String name = nextEntry.getName();
// only extract files
if (!name.endsWith("/")) {
final File nextFile = new File(target, name);
// create directories
final File parent = nextFile.getParentFile();
if (parent != null) {
parent.mkdirs();
}
// write file
try (OutputStream targetStream = new FileOutputStream(nextFile)) {
copy(zipStream, targetStream);
}
}
}
}
private static void copy(final InputStream source, final OutputStream target) throws IOException {
final int bufferSize = 4 * 1024;
final byte[] buffer = new byte[bufferSize];
int nextCount;
while ((nextCount = source.read(buffer)) >= 0) {
target.write(buffer, 0, nextCount);
}
}
}