Search code examples
javacompressionziptar

Make tar file by Java


I want to use Java to compress a folder to a tar file (in programmatic way). I think there must be an open source or library to do it. However, I cannot find such method.

Alternatively, could I make a zip file and rename its extended name as .tar?

Anyone could suggest a library to do it? Thanks!


Solution

  • You can use the jtar - Java Tar library.

    Taken from their site:

    JTar is a simple Java Tar library, that provides an easy way to create and read tar files using IO streams. The API is very simple to use and similar to the java.util.zip package.

    An example, also from their site:

       // Output file stream
       FileOutputStream dest = new FileOutputStream( "c:/test/test.tar" );
    
       // Create a TarOutputStream
       TarOutputStream out = new TarOutputStream( new BufferedOutputStream( dest ) );
    
       // Files to tar
       File[] filesToTar=new File[2];
       filesToTar[0]=new File("c:/test/myfile1.txt");
       filesToTar[1]=new File("c:/test/myfile2.txt");
    
       for(File f:filesToTar){
          out.putNextEntry(new TarEntry(f, f.getName()));
          BufferedInputStream origin = new BufferedInputStream(new FileInputStream( f ));
    
          int count;
          byte data[] = new byte[2048];
          while((count = origin.read(data)) != -1) {
             out.write(data, 0, count);
          }
    
          out.flush();
          origin.close();
       }
    
       out.close();