How to zip a file while writing to it?

北城以北 提交于 2019-12-07 00:49:58

问题


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.


回答1:


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();



回答2:


Wrap another OutputStream in a ZipOutputStream (or GZIPOutputStream), and call the write methods on the ZipOutputStream.




回答3:


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.




回答4:


This is commonly done for web applications using filters:

http://tim.oreilly.com/pub/a/onjava/2003/11/19/filters.html



来源:https://stackoverflow.com/questions/4308276/how-to-zip-a-file-while-writing-to-it

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!