Skip to content

Instantly share code, notes, and snippets.

@Lokua
Created December 17, 2015 03:07
Show Gist options
  • Save Lokua/7a4d51bbce11a11251e3 to your computer and use it in GitHub Desktop.
Save Lokua/7a4d51bbce11a11251e3 to your computer and use it in GitHub Desktop.
zip helpers
package my.big.fucking.package;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;
public class ZipHelpers {
/**
* Create a byte array of a single zipped "file".
* For multiple files @see zipBytes(String[] filenames, String[] contents)
*
* To ensure Spring sends an actual zipfile, use
* <code>@RequestMapping(...blah, produces = "application/zip")</code>
* add an attachment header:
* <code>response.addHeader("Content-Disposition", "attachment; filename=example.zip");</code>
* and return the results of zipBytes
*
* @param filename the name for compressed @param bytes
* @param bytes the contents of "file" @param filename
* @return a byte array suitable to be returned from Spring Controller
* @throws IOException
*/
public static byte[] zipBytes(String filename, byte[] bytes) throws IOException {
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
ZipOutputStream zipOutputStream = new ZipOutputStream(byteArrayOutputStream);
ZipEntry entry = new ZipEntry(filename);
entry.setSize(bytes.length);
zipOutputStream.putNextEntry(entry);
zipOutputStream.write(bytes, 0, bytes.length);
zipOutputStream.closeEntry();
zipOutputStream.close();
return byteArrayOutputStream.toByteArray();
}
/**
* Create a byte array of multiple zipped "files". @see #zipBytes(String filename, byte[] bytes)
* for instructions on how to make this work with Spring.
*
* @param filenames list of filenames, one for each index of @param contents
* @param contents list of file contents, one index for each filename in @param filenames
* @return a byte array suitable to be returned from Spring Controller
* @throws IOException
*/
public static byte[] zipBytes(String[] filenames, String[] contents) throws IOException {
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
ZipOutputStream zipOutputStream = new ZipOutputStream(byteArrayOutputStream);
for (int i = 0; i < filenames.length; i++) {
byte[] content = contents[i].getBytes();
int contentLength = content.length;
ZipEntry entry = new ZipEntry(filenames[i]);
entry.setSize(contentLength);
zipOutputStream.putNextEntry(entry);
zipOutputStream.write(content, 0, contentLength);
zipOutputStream.closeEntry();
}
zipOutputStream.close();
return byteArrayOutputStream.toByteArray();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment