Skip to content

Instantly share code, notes, and snippets.

@aspose-com-gists
Created May 18, 2024 16:39
Show Gist options
  • Save aspose-com-gists/3b7c7990b215ed7a22a8c1390e104773 to your computer and use it in GitHub Desktop.
Save aspose-com-gists/3b7c7990b215ed7a22a8c1390e104773 to your computer and use it in GitHub Desktop.
Convert ZIP to TAR.GZ in Java Programmatically
package com.example;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import com.aspose.zip.Archive;
import com.aspose.zip.ArchiveEntry;
import com.aspose.zip.TarArchive;
import com.aspose.zip.exceptions.IOException;
public class Main {
// Convert ZIP to TAR.GZ in Java
public static void main(String[] args) throws java.io.IOException {
String dir = "/files/";
// Create an instance of the Archive class and load the source ZIP file.
try (Archive source = new Archive(dir+"sample.zip")) {
// Instantiate an object of the TarArchive class.
try (TarArchive tar = new TarArchive()) {
// Get the entries of RarArchiveEntry type constituting the rar archive by calling the getEntries method.
for (ArchiveEntry entry : source.getEntries()) {
if (!entry.isDirectory()) {
ByteArrayOutputStream out = new ByteArrayOutputStream();
try (java.io.InputStream mem = entry.open()) {
byte[] b = new byte[8192];
int bytesRead;
while (0 < (bytesRead = mem.read(b, 0, b.length))) {
out.write(b, 0, bytesRead);
}
}
// Invoke the createEntry method to create a single entry within the archive.
tar.createEntry(entry.getName(), new ByteArrayInputStream(out.toByteArray()));
}
}
// Save as the TAR.GZ archive by calling the saveGzipped method.
tar.saveGzipped(dir+"result.tar.gz");
}
} catch (IOException ex) {
System.out.println(ex);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment