You are viewing denis_tsyplakov

Денис Цыплаков - How to write ZIP file using pipe and nio [entries|archive|friends|userinfo]
Денис Цыплаков

[ userinfo | livejournal userinfo ]
[ archive | journal archive ]

How to write ZIP file using pipe and nio [Aug. 7th, 2009|10:40 am]
Previous Entry Add to Memories Share Next Entry
[Tags|]
[mood |productive]

Task - we need to create zip file in servlet container and put it into servlet outputstream without storing the whole zip file in memory or HDD.

package test;

import java.io.FileOutputStream;
import java.nio.ByteBuffer;
import java.nio.channels.Channels;
import java.nio.channels.Pipe;
import java.nio.channels.ReadableByteChannel;
import java.nio.channels.WritableByteChannel;
import java.util.logging.Logger;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;

/**
 * Author: Denis Tsyplakov Datetime: Aug 7, 2009 9:33:42 AM
 */
public class PipeDemo {

    static Logger log = Logger.getLogger(PipeDemo.class.getName());

    public static void main(String[] argv)
            throws Exception {
        FileOutputStream fos = new FileOutputStream("C:\\tmp\\1.zip");
        try {
            Pipe pipe = Pipe.open();

            WritableByteChannel out = Channels.newChannel(fos);

            ZipStreamWriter worker = new ZipStreamWriter(pipe.sink());
            worker.start();

            ReadableByteChannel workerChannel = (pipe.source());
            ByteBuffer buffer = ByteBuffer.allocate(1024*8);

            while (workerChannel.read(buffer) >= 0) {
                buffer.flip();
                out.write(buffer);
                buffer.clear();
            }
        }
        finally {
            fos.close();
        }
    }

    private static class ZipStreamWriter extends Thread {
        WritableByteChannel channel;

        ZipStreamWriter(WritableByteChannel channel) {
            this.channel = channel;
        }

        public void run() {
            try {
                ZipOutputStream zos = new ZipOutputStream(Channels.newOutputStream(channel));
                try {
                    zos.putNextEntry(new ZipEntry("test.txt"));
                    zos.write("This is test file content".getBytes());
                    zos.closeEntry();
                }
                finally {
                    zos.close();
                    channel.close();
                }
            } catch (Exception e) {
                log.severe(e.toString());
            }
        }

    }
}
linkReply

Comments:
From: sianamber
2009-12-13 12:45 pm (UTC)

(Link)

С Днем Рождения!
From: mutu26
2010-08-21 10:25 pm (UTC)

(Link)

Like situation is very usual for me. I quite often with archives on my work. Luckily I found out the solution similar issues - repair zip file. I observed it on an one soft community. It impressed on me within minutes after I had extracted it on my PC. Probably it will be so effective for you.