How to Zip Multiple Files in Java


Here this example demonstrates how to zip multiple files.

Source Code

package com.beginner.examples;

import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;

public class ZipMultipleFile {

	public static void main(String[] args) {
		
		List files = new ArrayList();
		files.add("e:/contract/Asset.sol");
		files.add("e:/contract/Main.sol");
		doZipMultipleFile(files);
	}
	
	/**
	 * @brief: Zip multiple files using ZipOutputStream class. 
	 *         putNextEntry() method starts adding into the zip, 
	 *         and ZipEntry represents a file entry into the zip
	 * @param files
	 */
	public static void doZipMultipleFile(List files) {
		try {
			FileOutputStream fileOutPutStream = new FileOutputStream("e:/testing.zip");
			ZipOutputStream zipOutputStream = new ZipOutputStream(new BufferedOutputStream(fileOutPutStream));
			FileInputStream fileInputStream;
			for(String filePath:files){
                File input = new File(filePath);
                fileInputStream = new FileInputStream(input);
                ZipEntry ze = new ZipEntry(input.getName());
                System.out.println("Zipping the file: "+input.getName());
                zipOutputStream.putNextEntry(ze);
                byte[] tmp = new byte[4*1024];
                int size = 0;
                while((size = fileInputStream.read(tmp)) != -1){
                	zipOutputStream.write(tmp, 0, size);
                }
                zipOutputStream.flush();
                fileOutPutStream.close();
            }
		
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		
	}
}

References

Imported packages in Java documentation:

Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments