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
File
object for the file that needs to be tarred and gzipped (test.txt
in this case). - Creates a
FileOutputStream
object for the tar.gz file (test.tar.gz
in this case). - Creates a
GZIPOutputStream
object, which compresses the contents of the tar file. - Creates a
TarOutputStream
object, which is used to write the tar file. - Creates a
TarEntry
object 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 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 the command line to tar and distribute files?
- How can I use tar commands to 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?
- How do I use the Unix tar xvf command to extract files?
- How do I create a tar.zip file in Unix?
- How do I use the command line to tar and zip a file?
- How do I use gzip, tar, and zip to compress files?
See more codes...