Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to zip a file while writing to it?

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.

like image 260
Andrei Avatar asked Nov 29 '10 21:11

Andrei


1 Answers

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();
like image 152
pkaeding Avatar answered Oct 31 '22 17:10

pkaeding