cli-tarHow do I tar and gzip a file in Java?
To tar and gzip a file in Java, you can use the java.util.zip package. Here's an example of how to create a tar.gz file from a file:
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.zip.GZIPOutputStream;
import java.util.zip.TarEntry;
import java.util.zip.TarOutputStream;
public class TarGzExample {
  public static void main(String[] args) throws IOException {
    // Create a tar.gz file from the file
    File inputFile = new File("test.txt");
    File outputFile = new File("test.tar.gz");
    FileOutputStream fos = new FileOutputStream(outputFile);
    GZIPOutputStream gzos = new GZIPOutputStream(fos);
    TarOutputStream tos = new TarOutputStream(gzos);
    // Create the tar entry
    TarEntry tarEntry = new TarEntry(inputFile, inputFile.getName());
    tos.putNextEntry(tarEntry);
    // Write the file content
    FileInputStream fis = new FileInputStream(inputFile);
    byte[] buffer = new byte[1024];
    int length;
    while ((length = fis.read(buffer)) > 0) {
      tos.write(buffer, 0, length);
    }
    // Close the streams
    tos.close();
    fis.close();
    gzos.close();
    fos.close();
  }
}
This code does the following:
- Creates a 
Fileobject for the file that needs to be tarred and gzipped (test.txtin this case). - Creates a 
FileOutputStreamobject for the tar.gz file (test.tar.gzin this case). - Creates a 
GZIPOutputStreamobject, which compresses the contents of the tar file. - Creates a 
TarOutputStreamobject, which is used to write the tar file. - Creates a 
TarEntryobject for the file that needs to be tarred and gzipped. - Writes the content of the file to the tar file.
 - Closes all the streams.
 
After running this code, a tar.gz file (test.tar.gz) will be created.
Helpful links
More of Cli Tar
- How can I use tar commands to zip a file?
 - How do I use the tar command line in Windows 10?
 - How do I use the tar command on Windows?
 - How do I use the command line to tar and zip files?
 - How do I use the shell to tar and zip files?
 - How do I use tar gzip with a password?
 - How can I fix an unexpected end of file error when compressing a file with tar and gzip?
 - How do I use the command line to tar and zip a file?
 - How do I use the Unix tar zip command?
 - How do I use the command line to tar and zip a file?
 
See more codes...