import java.io.ByteArrayOutputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;
public class Zipper
{
public static byte[] zip(String[] names, byte[][] data) throws IOException
{
if (names == null || data == null || names.length == 0 || names.length < data.length)
throw new IllegalArgumentException("Arguemnts are null or empty or names less than data");
ByteArrayOutputStream outZipStream = new ByteArrayOutputStream();
ZipOutputStream out = new ZipOutputStream(outZipStream);
int l = data.length;
for (int i=0; i < l; i++)
{
out.putNextEntry(new ZipEntry(names[i]));
out.write(data[i]);
out.closeEntry();
}
out.close();
return outZipStream.toByteArray();
}
public static void main(String[] args) throws IOException
{
byte[] file1Data = "File 1 content".getBytes("UTF-8");
byte[] file2Data = "File 2 content".getBytes("UTF-8");
byte[] zippedData = zip (new String[] {"file1.txt", "file2.txt"}, new byte[][] {file1Data, file2Data});
FileOutputStream fileOutputStream = new FileOutputStream("test.zip");
fileOutputStream.write(zippedData);
fileOutputStream.close();
}
}
25 December 2011
Zipping in Java
Labels:
java
Subscribe to:
Post Comments (Atom)
No comments:
Post a Comment