views:

913

answers:

1

I'm wanting to execute a program and as it runs read in it's output and pipe out the output into a zipped file. The output of the program can be quite large so the idea is to not hold too much in memory - just to send it to the zip as I get it.

+3  A: 
ZipOutputStream targetStream = new ZipOutputStream(fileToSaveTo);
ZipEntry entry = new ZipEntry(nameOfFileInZipFile);
targetStream.putNextEntry(entry);

byte[] dataBlock = new byte[1024];
int count = inputStream.read(dataBlock, 0, 1024);
while (count != -1) {
    targetStream.write(dataBlock, 0, count);
    count = inputStream.read(dataBlock, 0, 1024);
}

In otherwords:

  1. You create a ZipOutputStream, giving it the file you want to write to.
  2. You create a ZipEntry, which constitutes a file within that zip file. i.e. When you open myFile.zip, and there are 3 files in there, each file is a ZipEntry.

  3. You put that zipEntry into your ZipOutputStream

  4. Create a byte buffer to read your data into.
  5. Read from your inputStream into your byte buffer, and remember the count.
  6. While the count is not -1, write that byte byffer to your zipStream.
  7. Read the next line.

Close out your streams when you are done. Wrap it in a method as you see fit.

scubabbl