How do I create a zip file and add more than one entry to the zip file?

Finlay McWalter

You need to use the facilities of java.util.zip.ZipOutputStream and java.util.zip.ZipEntry. Here's a simple example that makes a zip file and writes three tiny text files into it.

import java.io.*;
import java.util.zip.*;

public class zipper {
    public static final void main(String [] args){
	try {
	    ZipOutputStream outStream = new ZipOutputStream (new 
		FileOutputStream("out.zip"));
	        
	    writeEntry(outStream, "f1.txt", "this is some text");
	    writeEntry(outStream, "f2.txt", "more text");
	    writeEntry(outStream, "f3.txt", "text, text, and yet more text");
	    
	    outStream.close();
	}
	catch(Exception e){
	    e.printStackTrace();
	}
    }

    static void writeEntry(ZipOutputStream stream,
			   String          filename,
			   String          text){
	try {
	    ZipEntry e1 = new ZipEntry(filename);
	    e1.setMethod(ZipEntry.DEFLATED);
	    stream.putNextEntry(e1);
	    stream.write(text.getBytes());
	    stream.closeEntry();
	}
	catch(IOException e){
	    e.printStackTrace();
	}
    }
}
0 Comments  (click to add your comment)
Comment and Contribute

 

 

 

 

 


(Maximum characters: 1200). You have 1200 characters left.

 

 

About | Sitemap | Contact