host.anzo.commons.utils.ZipUtils Maven / Gradle / Ivy
package host.anzo.commons.utils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.IOUtils;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.net.URI;
import java.nio.file.*;
import java.util.HashMap;
import java.util.Map;
import java.util.zip.GZIPInputStream;
import java.util.zip.GZIPOutputStream;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;
/**
* @author ANZO
* @since 10.03.2017
*/
@Slf4j
public class ZipUtils {
/**
* Returns a zip file system
* @param zipFilename to construct the file system from
* @param create true if the zip file should be created
* @return a zip file system
* @throws IOException if an I/O error occurs creating the file system
*/
public static FileSystem createZipFileSystem(String zipFilename, boolean create) throws IOException {
// convert the filename to a URI
final Path path = Paths.get(zipFilename);
final URI uri = URI.create("jar:file:" + path.toUri().getPath().replace(" ","%20"));
final Map env = new HashMap<>();
if (create) {
env.put("create", "true");
}
return FileSystems.newFileSystem(uri, env);
}
/**
* Add file to zip archive
* @param fileName path to file
* @param zos zip archive output stream
*/
public static void putFileToZipStream(String fileName, ZipOutputStream zos) {
try {
final File file = new File(fileName);
if (file.exists()) {
zos.putNextEntry(new ZipEntry(new File(fileName).getName()));
final byte[] bytes = Files.readAllBytes(Paths.get(fileName));
zos.write(bytes, 0, bytes.length);
zos.closeEntry();
}
}
catch (IOException e) {
log.error("Error while putFileToZipStream() fileName=[{}]", fileName, e);
}
}
/**
* @param data bytes to compress
* @return compressed bytes
*/
public static byte[] compress(byte[] data) {
if(data == null || data.length == 0)
return null;
try(ByteArrayOutputStream bos = new ByteArrayOutputStream();
final GZIPOutputStream gzip = new GZIPOutputStream(bos)) {
gzip.write(data);
return bos.toByteArray();
} catch(IOException e) {
log.error("Error while compress data", e);
return null;
}
}
/**
* @param data bytes to decompress
* @return decompressed bytes
*/
public static byte[] decompress(byte[] data) {
if(data == null || data.length == 0)
return null;
try(ByteArrayInputStream bis = new ByteArrayInputStream(data);
GZIPInputStream gis = new GZIPInputStream(bis)) {
return IOUtils.toByteArray(gis);
}catch (IOException e) {
log.error("Error while decompress data", e);
}
return null;
}
}