Comprimere e decomprimere file tar.gz con Java
Java di default non ha classi per la compressione / decompressione dei file tar.gz.
Però possiamo usare Apache Commons Compress.
Se usate Maven:
<dependencies>
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-compress</artifactId>
<version>1.20</version>
</dependency>
</dependencies>
Qui sotto un codice con le due funzioni:
import org.apache.commons.compress.archivers.ArchiveEntry;
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.compressors.gzip.GzipCompressorInputStream;
import org.apache.commons.compress.compressors.gzip.GzipCompressorOutputStream;
import java.io.*;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardCopyOption;
public class Main {
public static void main(String[] args) {
Path pathOut = Paths.get("/home/user/file.tar.gz");
Path pathInput = Paths.get("/home/user/file.xls");
Path target = Paths.get("/home/user/test_comp");
try {
compress(pathInput, pathOut);
} catch (IOException ex) {
System.out.println("ERR: " + ex.getMessage());
}
System.out.println("COMPRESSIONE OK");
try {
decompress(pathOut, target);
} catch (IOException ex) {
System.out.println("ERR: " + ex.getMessage());
}
System.out.println("DE-COMPRESSIONE OK");
}
private static void compress(Path input, Path output) throws IOException {
try (OutputStream fOut = Files.newOutputStream(output);
BufferedOutputStream buffOut = new BufferedOutputStream(fOut);
GzipCompressorOutputStream gzOut = new GzipCompressorOutputStream(buffOut);
TarArchiveOutputStream tOut = new TarArchiveOutputStream(gzOut)) {
TarArchiveEntry tarEntry = new TarArchiveEntry(input.toFile(), input.getFileName().toString());
tOut.putArchiveEntry(tarEntry);
Files.copy(input, tOut);
tOut.closeArchiveEntry();
tOut.finish();
}
}
private static void decompress(Path input, Path output) throws IOException {
try (InputStream fi = Files.newInputStream(input);
BufferedInputStream bi = new BufferedInputStream(fi);
GzipCompressorInputStream gzi = new GzipCompressorInputStream(bi);
TarArchiveInputStream ti = new TarArchiveInputStream(gzi)) {
ArchiveEntry entry;
while ((entry = ti.getNextEntry()) != null) {
Path targetDirResolved = output.resolve(entry.getName());
Path normalizePath = targetDirResolved.normalize();
if (entry.isDirectory()) {
Files.createDirectories(normalizePath);
} else {
Path parent = normalizePath.getParent();
if (parent != null) {
if (Files.notExists(parent)) {
Files.createDirectories(parent);
}
}
Files.copy(ti, normalizePath, StandardCopyOption.REPLACE_EXISTING);
}
}
}
}
}
Enjoy!
java apache commons compress tar.gz
Commentami!