May 30, 2017

Compress folders/files and create .tar.gz (Tar archive with GunZip Compression) and .zip (ZIP compression) file in Java

Hi friends,

Today I will explain how easily we can compress files and folders in java.

I have used a third part library which so simple to use.

Download the .jar from the following URL
https://rauschig.org/jarchivelib/download.html

Now, create a java class and create .tar.gz and .zip files.

Sample source code

package gunziptest;

import java.io.File;
import java.io.IOException;
import java.util.logging.Level;
import java.util.logging.Logger;
import org.rauschig.jarchivelib.ArchiveFormat;
import org.rauschig.jarchivelib.Archiver;
import org.rauschig.jarchivelib.ArchiverFactory;
import org.rauschig.jarchivelib.CompressionType;

/**
 *
 * @author psrdotcom
 */
public class GunZipTest {

    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) {
        // Archive file name
        String archiveName = "archive";
        // test is destination folder
        File destination = new File("test");
        // source folder has files and sub-folders
        File archive = null;
        
        // zip compression
        Archiver archiver = ArchiverFactory.createArchiver(ArchiveFormat.ZIP);
        try {
            archive = archiver.create(archiveName, destination, source);
            if(archive != null && archive.isFile()) {
                System.out.println("gunziptest.GunZipTest.main()" + "zip file created");
            }
        } catch (IOException ex) {
            Logger.getLogger(GunZipTest.class.getName()).log(Level.SEVERE, null, ex);
        }

        // tar.gz compression
        archiver = ArchiverFactory.createArchiver(ArchiveFormat.TAR, CompressionType.GZIP);
        try {
            archive = archiver.create(archiveName, destination, source);
            if(archive != null && archive.isFile()) {
                System.out.println("gunziptest.GunZipTest.main()" + "zip file created");
            }
        } catch (IOException ex) {
            Logger.getLogger(GunZipTest.class.getName()).log(Level.SEVERE, null, ex);
        }
    }
}

Hope, you will find this useful.

Please send your review and feedback to psrdotcom@gmail.com

No comments:

Featured Post

Java Introdcution

Please send your review and feedback to psrdotcom@gmail.com