Create TAR Archive Example

This program demonstrates creating a TAR archive.

Problem Statement

Write a Java program that creates a TAR archive using Apache Commons Compress.

Source Code

1 import java.io.*;
2 import org.apache.commons.compress.archivers.tar.*;
3 public class TarCreateExample {
4 public static void main(String[] args) {
5 System.out.println("Eduinq TAR Create Example");
6 try(FileOutputStream fos=new FileOutputStream("archive.tar");
7 TarArchiveOutputStream tos=new TarArchiveOutputStream(fos)) {
8 addFile(tos,"file1.txt");
9 addFile(tos,"file2.txt");
10 System.out.println("Eduinq TAR Created Successfully");
11 } catch(Exception e){ System.out.println("Eduinq Exception: "+e.getMessage()); }
12 }
13 static void addFile(TarArchiveOutputStream tos,String filename) throws IOException {
14 File file=new File(filename);
15 TarArchiveEntry entry=new TarArchiveEntry(file,file.getName());
16 tos.putArchiveEntry(entry);
17 FileInputStream fis=new FileInputStream(file);
18 byte[] buffer=new byte[1024]; int len;
19 while((len=fis.read(buffer))!=-1){ tos.write(buffer,0,len); }
20 fis.close(); tos.closeArchiveEntry();
21 }
22 }

Program Output

					Eduinq TAR Create Example
Eduinq TAR Created Successfully
				

Explanation

Uses TarArchiveOutputStream to create archive. - Adds multiple files into TAR. - Exception handling ensures safe operations. - In enterprise systems, TAR archives package large datasets. Conclusion: Shows creating TAR archives.

Quick Links to Explore