使用apache.commons.compress对文件进行压缩与解压缩的不同方式
依赖
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-compress</artifactId>
<version>1.21</version>
</dependency>
话不多说,直接上代码
package com.common.utils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.compress.archivers.ArchiveEntry;
import org.apache.commons.compress.archivers.ArchiveInputStream;
import org.apache.commons.compress.archivers.ArchiveOutputStream;
import org.apache.commons.compress.archivers.tar.TarArchiveEntry;
import org.apache.commons.compress.archivers.tar.TarArchiveInputStream;
import org.apache.commons.compress.archivers.tar.TarArchiveOutputStream;
import org.apache.commons.compress.archivers.zip.ZipArchiveEntry;
import org.apache.commons.compress.archivers.zip.ZipArchiveInputStream;
import org.apache.commons.compress.archivers.zip.ZipArchiveOutputStream;
import org.apache.commons.compress.compressors.gzip.GzipCompressorOutputStream;
import org.apache.commons.compress.compressors.gzip.GzipCompressorInputStream;
import org.apache.commons.compress.compressors.lz4.FramedLZ4CompressorInputStream;
import org.apache.commons.compress.compressors.lz4.FramedLZ4CompressorOutputStream;
import org.apache.commons.compress.compressors.snappy.FramedSnappyCompressorInputStream;
import org.apache.commons.compress.compressors.snappy.FramedSnappyCompressorOutputStream;
import org.apache.commons.compress.utils.IOUtils;
import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.*;
import java.nio.file.*;
import java.nio.file.attribute.BasicFileAttributes;
import java.util.Objects;
import java.util.zip.*;
@Slf4j
public class CommonsCompressUtil {
public static class Gzip {
public static InputStream compress(byte[] sourceFile) {
long d1 = System.currentTimeMillis();
ByteArrayOutputStream compressedOutput = new ByteArrayOutputStream();
try {
ByteArrayInputStream sourceInput = new ByteArrayInputStream(sourceFile);
GzipCompressorOutputStream gzOut = new GzipCompressorOutputStream(compressedOutput);
int buffersize = 10240;
final byte[] buffer = new byte[buffersize];
int n;
while (-1 != (n = sourceInput.read(buffer))) {
gzOut.write(buffer, 0, n);
}
gzOut.finish();
} catch (IOException e) {
log.info("压缩失败,原因:{}", e.getMessage());
}
ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(compressedOutput.toByteArray());
log.info("压缩完毕,耗时:{}ms,", (System.currentTimeMillis() - d1));
return byteArrayInputStream;
}
public static InputStream uncompress(byte[] sourceFile) {
long d1 = System.currentTimeMillis();
ByteArrayInputStream compressedInput = new ByteArrayInputStream(sourceFile);
ByteArrayOutputStream decompressedOutput = new ByteArrayOutputStream();
try {
GzipCompressorInputStream gzIn = new GzipCompressorInputStream(compressedInput);
byte[] buffer = new byte[1024];
int n;
while (-1 != (n = gzIn.read(buffer))) {
decompressedOutput.write(buffer, 0, n);
}
} catch (Exception e) {
log.info("解压缩失败,原因:{}", e.getMessage());
}
ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(decompressedOutput.toByteArray());
log.info("压缩完毕,耗时:{}ms,", (System.currentTimeMillis() - d1));
return byteArrayInputStream;
}
}
public static class LZ4 {
public static InputStream compress(byte[] sourceFile) {
long d1 = System.currentTimeMillis();
ByteArrayInputStream compressedInput = new ByteArrayInputStream(sourceFile);
ByteArrayOutputStream decompressedOutput = new ByteArrayOutputStream();
try (
FramedLZ4CompressorOutputStream lzOut = new FramedLZ4CompressorOutputStream(decompressedOutput);) {
int buffersize = 10240;
final byte[] buffer = new byte[buffersize];
int n = 0;
while (-1 != (n = compressedInput.read(buffer))) {
lzOut.write(buffer, 0, n);
}
} catch (IOException e) {
log.info("压缩失败,原因:{}", e.getMessage());
}
ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(decompressedOutput.toByteArray());
log.info("压缩完毕,耗时:{}ms,", (System.currentTimeMillis() - d1));
return byteArrayInputStream;
}
public static InputStream uncompress(byte[] sourceFile) {
long d1 = System.currentTimeMillis();
ByteArrayInputStream compressedInput = new ByteArrayInputStream(sourceFile);
ByteArrayOutputStream decompressedOutput = new ByteArrayOutputStream();
try (
FramedLZ4CompressorInputStream zIn = new FramedLZ4CompressorInputStream(compressedInput);) {
int buffersize = 10240;
final byte[] buffer = new byte[buffersize];
int n = 0;
while (-1 != (n = zIn.read(buffer))) {
decompressedOutput.write(buffer, 0, n);
}
} catch (IOException e) {
log.info("解压缩失败,原因:{}", e.getMessage());
}
ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(decompressedOutput.toByteArray());
log.info("压缩完毕,耗时:{}ms,", (System.currentTimeMillis() - d1));
return byteArrayInputStream;
}
}
public static class Snappy {
public static InputStream compress(byte[] sourceFile) {
long d1 = System.currentTimeMillis();
ByteArrayInputStream compressedInput = new ByteArrayInputStream(sourceFile);
ByteArrayOutputStream decompressedOutput = new ByteArrayOutputStream();
try (
FramedSnappyCompressorOutputStream snOut = new FramedSnappyCompressorOutputStream(decompressedOutput);) {
int buffersize = 10240;
final byte[] buffer = new byte[buffersize];
int n = 0;
while (-1 != (n = compressedInput.read(buffer))) {
snOut.write(buffer, 0, n);
}
} catch (IOException e) {
log.info("压缩失败,原因:{}", e.getMessage());
}
ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(decompressedOutput.toByteArray());
log.info("压缩完毕,耗时:{}ms,", (System.currentTimeMillis() - d1));
return byteArrayInputStream;
}
public static InputStream uncompress(byte[] sourceFile) {
long d1 = System.currentTimeMillis();
ByteArrayInputStream compressedInput = new ByteArrayInputStream(sourceFile);
ByteArrayOutputStream decompressedOutput = new ByteArrayOutputStream();
try (
FramedSnappyCompressorInputStream zIn = new FramedSnappyCompressorInputStream(compressedInput);) {
int buffersize = 10240;
final byte[] buffer = new byte[buffersize];
int n = 0;
while (-1 != (n = zIn.read(buffer))) {
decompressedOutput.write(buffer, 0, n);
}
} catch (IOException e) {
log.info("解压缩失败,原因:{}", e.getMessage());
}
ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(decompressedOutput.toByteArray());
log.info("压缩完毕,耗时:{}ms,", (System.currentTimeMillis() - d1));
return byteArrayInputStream;
}
}
public static class Zip {
public static void compress(String sourceFile, String targetFile) {
long d1 = System.currentTimeMillis();
ByteArrayOutputStream fos = new ByteArrayOutputStream();
ZipArchiveOutputStream bos = new ZipArchiveOutputStream(fos);
try (ArchiveOutputStream aos = new ZipArchiveOutputStream(bos);) {
Path dirPath = Paths.get(sourceFile);
Files.walkFileTree(dirPath, new SimpleFileVisitor<Path>() {
@Override
public FileVisitResult preVisitDirectory(Path dir, BasicFileAttributes attrs) throws IOException {
ArchiveEntry entry = new ZipArchiveEntry(dir.toFile(), dirPath.relativize(dir).toString());
aos.putArchiveEntry(entry);
aos.closeArchiveEntry();
return super.preVisitDirectory(dir, attrs);
}
@Override
public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {
ArchiveEntry entry = new ZipArchiveEntry(
file.toFile(), dirPath.relativize(file).toString());
aos.putArchiveEntry(entry);
IOUtils.copy(new FileInputStream(file.toFile()), aos);
aos.closeArchiveEntry();
return super.visitFile(file, attrs);
}
});
} catch (IOException e) {
System.out.println("压缩失败,原因:" + e.getMessage());
}
System.out.println("压缩完毕,耗时:" + (System.currentTimeMillis() - d1) + " ms");
}
public static void uncompress(String zipPath, String descDir) {
long d1 = System.currentTimeMillis();
try (InputStream fis = Files.newInputStream(Paths.get(zipPath));
InputStream bis = new BufferedInputStream(fis);
ArchiveInputStream ais = new ZipArchiveInputStream(bis);
) {
ArchiveEntry entry;
while (Objects.nonNull(entry = ais.getNextEntry())) {
if (!ais.canReadEntryData(entry)) {
continue;
}
String name = descDir + File.separator + entry.getName();
File f = new File(name);
if (entry.isDirectory()) {
if (!f.isDirectory() && !f.mkdirs()) {
f.mkdirs();
}
} else {
File parent = f.getParentFile();
if (!parent.isDirectory() && !parent.mkdirs()) {
throw new IOException("failed to create directory " + parent);
}
try (OutputStream o = Files.newOutputStream(f.toPath())) {
IOUtils.copy(ais, o);
}
}
}
} catch (IOException e) {
e.printStackTrace();
System.out.println("解压失败,原因:" + e.getMessage());
}
System.out.println("解压完毕,耗时:" + (System.currentTimeMillis() - d1) + " ms");
}
}
public static class Tar {
public static void compress(String sourceFile, String targetFile) {
long d1 = System.currentTimeMillis();
try (OutputStream fos = new FileOutputStream(targetFile);
OutputStream bos = new BufferedOutputStream(fos);
ArchiveOutputStream aos = new TarArchiveOutputStream(bos);) {
Path dirPath = Paths.get(sourceFile);
Files.walkFileTree(dirPath, new SimpleFileVisitor<Path>() {
@Override
public FileVisitResult preVisitDirectory(Path dir, BasicFileAttributes attrs) throws IOException {
ArchiveEntry entry = new TarArchiveEntry(dir.toFile(), dirPath.relativize(dir).toString());
aos.putArchiveEntry(entry);
aos.closeArchiveEntry();
return super.preVisitDirectory(dir, attrs);
}
@Override
public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {
ArchiveEntry entry = new TarArchiveEntry(
file.toFile(), dirPath.relativize(file).toString());
aos.putArchiveEntry(entry);
IOUtils.copy(new FileInputStream(file.toFile()), aos);
aos.closeArchiveEntry();
return super.visitFile(file, attrs);
}
});
} catch (IOException e) {
System.out.println("压缩失败,原因:" + e.getMessage());
}
System.out.println("压缩完毕,耗时:" + (System.currentTimeMillis() - d1) + " ms");
}
public static void uncompress(String tarPath, String descDir) {
long d1 = System.currentTimeMillis();
try (InputStream fis = Files.newInputStream(Paths.get(tarPath));
InputStream bis = new BufferedInputStream(fis);
ArchiveInputStream ais = new TarArchiveInputStream(bis);
) {
ArchiveEntry entry;
while (Objects.nonNull(entry = ais.getNextEntry())) {
if (!ais.canReadEntryData(entry)) {
continue;
}
String name = descDir + File.separator + entry.getName();
File f = new File(name);
if (entry.isDirectory()) {
if (!f.isDirectory() && !f.mkdirs()) {
f.mkdirs();
}
} else {
File parent = f.getParentFile();
if (!parent.isDirectory() && !parent.mkdirs()) {
throw new IOException("failed to create directory " + parent);
}
try (OutputStream o = Files.newOutputStream(f.toPath())) {
IOUtils.copy(ais, o);
}
}
}
} catch (IOException e) {
e.printStackTrace();
System.out.println("解压失败,原因:" + e.getMessage());
}
System.out.println("解压完毕,耗时:" + (System.currentTimeMillis() - d1) + " ms");
}
}
public static class Deflaters {
public static InputStream compress(byte[] data) throws IOException {
ByteArrayOutputStream compressedDataStream = new ByteArrayOutputStream();
try (DeflaterOutputStream deflaterOutputStream = new DeflaterOutputStream(compressedDataStream, new Deflater(Deflater.BEST_COMPRESSION))) {
deflaterOutputStream.write(data);
deflaterOutputStream.finish();
deflaterOutputStream.flush();
}
InputStream compressedInputStream = new ByteArrayInputStream(compressedDataStream.toByteArray());
return compressedInputStream;
}
public static InputStream uncompress(byte[] compressedData) throws IOException {
ByteArrayOutputStream decompressedDataStream = new ByteArrayOutputStream();
try (InflaterInputStream inflaterInputStream = new InflaterInputStream(new ByteArrayInputStream(compressedData), new Inflater())) {
byte[] buffer = new byte[1024];
int len;
while ((len = inflaterInputStream.read(buffer)) > 0) {
decompressedDataStream.write(buffer, 0, len);
}
}
InputStream decompressedInputStream = new ByteArrayInputStream(decompressedDataStream.toByteArray());
return decompressedInputStream;
}
}
}