Reputation: 73
Does anyone know of a way to zip a stream that you are writing to? I'm trying to avoid writing the file to the disk, and was wondering if I can just compress data as you are writing it to the stream.
The use case behind this is that the raw file is going to be very large and we want to avoid having to write the entire thing unzipped onto the disk.
Upvotes: 7
Views: 9087
Reputation: 308998
This is commonly done for web applications using filters:
http://tim.oreilly.com/pub/a/onjava/2003/11/19/filters.html
Upvotes: 0
Reputation: 15239
I have done this before in a webapp. I got a reference to the servlet OutputStream and then supplied that to the ZipOutputStream
. Then I just zipped. The zipped file was served up to the client browser. Easy.
Upvotes: 1
Reputation: 37663
I think you would be interested in ZipOutputStream. You can write to that stream, and then write it out to a zipped file.
Also, check out this tutorial for working with compressed (zipped) files in Java. Here is a snippet from that tutorial, which might be a helpful illustration:
BufferedInputStream origin = null;
FileOutputStream dest = new
FileOutputStream("c:\\zip\\myfigs.zip");
ZipOutputStream out = new ZipOutputStream(new
BufferedOutputStream(dest));
//out.setMethod(ZipOutputStream.DEFLATED);
byte data[] = new byte[BUFFER];
// get a list of files from current directory
File f = new File(".");
String files[] = f.list();
for (int i=0; i<files.length; i++) {
System.out.println("Adding: "+files[i]);
FileInputStream fi = new
FileInputStream(files[i]);
origin = new
BufferedInputStream(fi, BUFFER);
ZipEntry entry = new ZipEntry(files[i]);
out.putNextEntry(entry);
int count;
while((count = origin.read(data, 0,
BUFFER)) != -1) {
out.write(data, 0, count);
}
origin.close();
}
out.close();
Upvotes: 8
Reputation: 88826
Wrap another OutputStream
in a ZipOutputStream
(or GZIPOutputStream
), and call the write methods on the ZipOutputStream
.
Upvotes: 5