Skip to content

Instantly share code, notes, and snippets.

@shasisingh
Last active April 13, 2023 18:05
Show Gist options
  • Save shasisingh/c6e91ae02428d735043029b173198da1 to your computer and use it in GitHub Desktop.
Save shasisingh/c6e91ae02428d735043029b173198da1 to your computer and use it in GitHub Desktop.
GzipCompressor and TarArchive
public static void createTarGzipFiles(List<Path> files, Path output) {
try (OutputStream fOut = Files.newOutputStream(output);
BufferedOutputStream buffOut = new BufferedOutputStream(fOut);
GzipCompressorOutputStream gzOut = new GzipCompressorOutputStream(buffOut);
TarArchiveOutputStream tOut = new TarArchiveOutputStream(gzOut)) {
for (Path path : Collections.unmodifiableList(files)) {
if (!Files.isRegularFile(path)) {
throw new IOException("Support only file!");
}
var tarEntry = new TarArchiveEntry(path.toFile(), path.getFileName().toString());
tOut.putArchiveEntry(tarEntry);
Files.copy(path, tOut);
tOut.closeArchiveEntry();
}
tOut.finish();
}
catch (IOException e){
throw new RuntimeException(e);
}
}
public static void extract(String filename) {
try (FileInputStream fis = new FileInputStream(filename); BufferedInputStream bis = new BufferedInputStream(fis)) {
ArchiveInputStream input = new ArchiveStreamFactory().createArchiveInputStream(bis);
if (input instanceof TarArchiveInputStream) {
System.out.println("It is a tar input stream");
TarArchiveInputStream tarInput = (TarArchiveInputStream) input;
TarArchiveEntry entry = tarInput.getNextTarEntry();
while (entry != null) {
String name = entry.getName();
System.out.println("Entry: " + name);
entry = tarInput.getNextTarEntry();
}
}else {
throw new UnsupportedOperationException("File is not tar. file:{" + filename + "}");
}
} catch (Exception e) {
e.printStackTrace();
}
}
public static void unTarGz(final Path pathInput, final Path pathOutput ) throws IOException {
TarArchiveInputStream tararchiveinputstream =
new TarArchiveInputStream(
new GzipCompressorInputStream(
new BufferedInputStream( Files.newInputStream( pathInput ) ) ) );
ArchiveEntry archiveentry;
pathOutput.toFile().mkdirs();
while( (archiveentry = tararchiveinputstream.getNextEntry()) != null ) {
Path pathEntryOutput = pathOutput.resolve( archiveentry.getName() );
if( archiveentry.isDirectory() ) {
if( !Files.exists( pathEntryOutput ) )
Files.createDirectory( pathEntryOutput );
}
else
Files.copy( tararchiveinputstream, pathEntryOutput );
}
tararchiveinputstream.close();
}
@shasisingh
Copy link
Author

based on org.apache.commons.compress

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment