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.
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();
在ZipOutputStream
(或GZIPOutputStream
)中包装另一个OutputStream
,并调用ZipOutputStream
上的write方法。
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.
This is commonly done for web applications using filters:
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.