java.util.zip Zip a file example


package test;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;

/**
 *
 * @author tunatore
 */
public class CreatingZIPfile {

    public void createZipFile() {

        try {

            File inputFile = new File(“C:\\test.txt”);
            File zipFile = new File(“C:\\compressed.zip”);

            //Create input and output streams
            FileInputStream inStream = new FileInputStream(inputFile);
            ZipOutputStream outStream = new ZipOutputStream(new FileOutputStream(zipFile));

            // Add a zip entry to the output stream
            outStream.putNextEntry(new ZipEntry(inputFile.getName()));

            byte[] buffer = new byte[Byte.MAX_VALUE];
            int bytesRead;

            //read from the input stream
            //write to the output stream
            while ((bytesRead = inStream.read(buffer)) > 0)
            {
                outStream.write(buffer, 0, bytesRead);
            }

            //Close zip entry and file streams
            outStream.closeEntry();

            outStream.close();
            inStream.close();

        } catch (IOException ex) {
            ex.printStackTrace();
        }
    }

    public static void main(String[] args)
    {
        new CreatingZIPfile().createZipFile();
    }
}

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s